javascript 替换 textarea 中选定的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3964710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replacing selected text in the textarea
提问by ming yeow
what is the best way to do this in jQuery? This should be a fairly common use case.
在 jQuery 中执行此操作的最佳方法是什么?这应该是一个相当普遍的用例。
- User selects text in a textarea
- He clicks on a link
- The text in the link replaces the selected text in the textarea
- 用户在 textarea 中选择文本
- 他点击了一个链接
- 链接中的文字替换了textarea中选中的文字
Any code will be much appreciated - I am having some issues with part 3.
任何代码都将不胜感激-我在第 3 部分遇到了一些问题。
回答by Tim Down
Here's how you can do it, in all major browsers. I've also got a jQuery plug-inthat includes this functionality. With that, the code would be
这是在所有主要浏览器中执行此操作的方法。我还有一个包含此功能的jQuery 插件。有了这个,代码将是
$("your_textarea_id").replaceSelectedText("NEW TEXT");
Here's a full stand-alone solution:
这是一个完整的独立解决方案:
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
function replaceSelectedText(el, text) {
var sel = getInputSelection(el), val = el.value;
el.value = val.slice(0, sel.start) + text + val.slice(sel.end);
}
var el = document.getElementById("your_textarea");
replaceSelectedText(el, "[NEW TEXT]");

