如何在文本区域中包装所选文本? [英] How to wrap selected text in a textarea?

查看:107
本文介绍了如何在文本区域中包装所选文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取用户选择的文本(仅在文本区域内)并对其进行操作,例如包装选择[#bold]selected text[/bold]?

How can I get the user selected text (just inside textarea) and apply actions to it something like wrap the selection [#bold]selected text[/bold]?

推荐答案

以Soufiane发布的内容为基础,下面是将代码转换为jquery并可以传递打开和关闭标签的功能:

Building off what Soufiane posted, here's the code translated to jquery with the ability to pass in the open and close tags:

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

使用方式如下:

wrapText("myTextArea", "[#bold]", "[/bold]");

这篇关于如何在文本区域中包装所选文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆