将标签放在用户突出显示的文本旁边 [英] Put a tags round user highlighted text?
问题描述
我需要获取用户选择的textarea区域,然后在其周围插入< a>
标签。
I need to get the user selected area of a textarea and then insert <a>
tags round it.
我用它来获取用户所选区域:
I use this to get the user selected area:
var textComponent = document.getElementById('article');
var selectedText;
if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
// Mozilla version
else if (textComponent.selectionStart != undefined)
{
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos)
}
现在,我知道我可以对用户选择的文本进行字符串搜索并在其周围插入标签,但是如果用户选择的文本在文本中出现两次会发生什么情况,例如。
Now, I know I can do a string search for the user selected text and insert a tags round it, but what happens if that user selected text appears twice in the text, for example.
您好,再见。
Hello to you, goodbye to you.
如果用户突出显示第二个'你'对于他们想要的链接,肯定是字符串替换会在'你'的每个实例周围放置一个标签。
If the user highlights the second 'you' for the link they want, surely a string replace would put a tags around every instance of 'you'.
最好的方法是什么?
推荐答案
You could use my jQuery plug-in for this (demo):
$("#article").surroundSelectedText('<a href="foo.html">', "</a>");
或者你可以使用 getInputSelection()
我发布在Stack Overflow上的函数几次在所有主流浏览器中获取选择开始和结束字符索引,然后在textarea的值
上进行字符串替换:
Alternatively you could use the getInputSelection()
function that I've posted on Stack Overflow a few times to get the selection start and end character indices in all major browsers and then do string substitution on the textarea's value
:
var sel = getInputSelection(textComponent);
var val = textComponent.value;
textComponent.value = val.slice(0, sel.start) +
'<a href="foo.html">' +
val.slice(sel.start, sel.end) +
"</a>" +
val.slice(sel.end);
这篇关于将标签放在用户突出显示的文本旁边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!