gpt4 book ai didi

javascript - 替换文本区域中的选定文本

转载 作者:可可西里 更新时间:2023-11-01 01:18:06 24 4
gpt4 key购买 nike

在 jQuery 中执行此操作的最佳方法是什么?这应该是一个相当常见的用例。

  1. 用户在文本区域中选择文本
  2. 他点击了一个链接
  3. 链接中的文本替换文本区域中的选定文本

任何代码将不胜感激 - 我在第 3 部分遇到了一些问题。

最佳答案

以下是您在所有主要浏览器中的操作方法。我还有一个 jQuery plug-in包括此功能。这样,代码将是

$("your_textarea_id").replaceSelectedText("NEW TEXT");

这是一个完整的独立解决方案:

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]");

关于javascript - 替换文本区域中的选定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com