我正在尝试 append <a>
当用户右键单击所选文本时,将其标记到所选文本中。我在堆栈中进行了搜索,没有找到匹配项。
最佳答案
跨浏览器可靠地处理选定的文本有点棘手。 Tim Down 的图书馆 Rangy在那里可能很有用,他消除了许多浏览器的特性。 (即使您不想使用该库,也可以研究它的技术。)
core Rangy demos 之一使用 the RangyRange#surroundContents
method 用元素包围选定的文本。演示中的代码如下所示:
function getFirstRange() {
var sel = rangy.getSelection();
return sel.rangeCount ? sel.getRangeAt(0) : null;
}
function surroundRange() {
var range = getFirstRange();
if (range) {
var el = document.createElement("span");
el.style.backgroundColor = "pink";
try {
range.surroundContents(el);
} catch(ex) {
if ((ex instanceof rangy.RangeException || Object.prototype.toString.call(ex) == "[object RangeException]") && ex.code == 1) {
alert("Unable to surround range because range partially selects a non-text node. See DOM Level 2 Range spec for more information.\n\n" + ex);
} else {
alert("Unexpected errror: " + ex);
}
}
}
}
您的做法大致相同,但使用 a
而不是 span
。
关于jquery - 使用 jquery 将某些内容 append 到选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9290205/