在用户突出显示的文本周围放置标签
Put a tags round user highlighted text?
我需要获取用户选择的文本区域,然后在它周围插入<a>
标签。
我用它来获取用户选择的区域:
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)
}
现在,我知道我可以对用户选择的文本进行字符串搜索并在其周围插入标签,但是例如,如果用户选择的文本在文本中出现两次会发生什么。
你好,再见。
如果用户突出显示他们想要的链接的第二个"你",字符串替换肯定会在每个"你"实例周围放置一个标签。
最好的方法是什么?
你可以使用我的jQuery插件(演示):
$("#article").surroundSelectedText('<a href="foo.html">', "</a>");
或者,您可以使用我在 Stack Overflow 上发布几次的 getInputSelection()
函数来获取所有主要浏览器中的选择开始和结束字符索引,然后在文本区域的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);
为什么要捕获所选文本? 您真正想要的是标签中的开始/结束位置。
var textComponent = document.getElementById('article');
var selectedText;
var startPos;
var endPos;
// the easy way
if (textComponent.selectionStart != undefined)
{
startPos = textComponent.selectionStart;
endPos = textComponent.selectionEnd;
}
// the hard way
else if (document.selection != undefined)
{
textComponent.focus();
var sel = document.selection.createRange();
var range = document.selection.createRange();
var stored_range = range.duplicate();
stored_range.moveToElementText(textComponent);
stored_range.setEndPoint( 'EndToEnd', range );
startPos = stored_range.text.length - range.text.length;
endPos = startPos + range.text.length;
}
// add in tags at startPos and endPos
var val = textComponent.value;
textComponent.value = val.substring(0, startPos) + "<a>" + val.substring(startPos, endPos) + "</a>" + val.substring(endPos);
根据此引用修改的 IE 代码。
编辑:注意Tim Down关于换行符的评论。 另外,可能使用他的索尔特,因为它更好。
相关文章:
- 如何将具有文本类型值的var放入jQuery函数中
- 如何在输入中选择的文本周围包装html标记
- 基于宽度的文本缩放
- 需要帮助从列表项中获取文本并放入输入框
- 如何使用jquery获取数字元素的文本并放入数组中
- ajax 返回的文本周围的未知引号
- 在用户突出显示的文本周围放置标签
- 分隔的文本框放回一个变量中并以不同的方式显示
- 如何使用 jQuery 将段落的原始文本格式放入 HTML 段落元素中
- 为什么用Javascript RegEx在文本周围包装标签会将标签显示为文本
- 分割抽取文本周围的双引号内的Eval语句在Imacros
- 无限循环到JS驱动文本缩放动画
- 如何使用jQuery在有换行符的文本周围添加span换行
- 在xcode中选定文本周围插入双引号
- 在不移动光标的情况下,在contentitable内的某些文本周围放置标记
- 在元素中选定的文本周围添加标记
- 根据偏移量创建文本周围的跨度
- 如何存储课程以外的下拉菜单和打开新的文本框放其他教育
- 将内部HTML转换为文本并放入文本区域不起作用
- 为什么在SELECT属性周围放一个DIV会很麻烦呢?