gpt4 book ai didi

javascript - 如何使用 javascript 将突出显示的单词包含在带有一些标签的文本区域中?

转载 作者:行者123 更新时间:2023-12-03 09:30:44 25 4
gpt4 key购买 nike

例如,假设我想突出显示文本区域字段中的文本 block ,然后用 <highlight>...</highlight> 将文本括起来。通过按链接来添加标签(例如 <highlight>(highlighted text appears here)</highlight> )——例如:

<textarea id="comment-body"></textarea>
<a href="#" class="highlight-words" onclick="highlightWords()">Highlight</a>

function highlightWords(){
// code for enclosing highlighted text in textarea appears here
}

有什么想法吗?

最佳答案

您可以使用 JavaScript selectionStartselectionEnd 属性来查找所选文本。这将为您提供开始和结束索引,您可以使用它们来更新字符串。

<textarea id="comment-body"></textarea>
<a href="#" class="highlight-words">Highlight</a>

$('a.highlight-words').click(function() {
var textComponent = document.getElementById('comment-body');
var fullText = document.getElementById('comment-body').value;
var selectedText;
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)

if (selectedText.length > 0) {
var newStr = fullText.substr(0, endPos) + '</highlight>' + fullText.substr(endPos);
newStr = newStr.substr(0, startPos) + '<highlight>' + newStr.substr(startPos);

textComponent.value = newStr;
}
});

此处演示:http://jsfiddle.net/rqy7e0qh/

关于javascript - 如何使用 javascript 将突出显示的单词包含在带有一些标签的文本区域中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31513895/

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