jQuery -在文本区域内插入字符串,然后选择其中的一部分

jQuery - inserting a string inside a textarea, then selecting a portion of it

本文关键字:选择 然后 一部分 字符串 文本 区域 插入 jQuery      更新时间:2023-09-26

就像SO有B按钮:

**strong text**

strong text将被自动选中,并且光标将定位在s前面

您可以使用我的Rangy Inputs jQuery插件,现在我终于有时间记录它了。使用它,下面的代码可以完成这项工作:

$textArea = $("#yourtextarea");
$textArea.focus();
$textArea.surroundSelectedText("**", "**");

这将选择与之前选择的相同的文本,这就是SO所做的。但是,如果你想在"s"前面加一个插入符号,那么你可以添加以下内容:

$textArea.collapseSelection(true);

jsFiddle示例:http://jsfiddle.net/AL7uY/