删除使用JavaScript添加到所选文本的高亮 [英] Remove highlight added to selected text using JavaScript?
本文介绍了删除使用JavaScript添加到所选文本的高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码使用JavaScript突出显示所选文本:
I highlighted selected text using JavaScript with the following code:
var sel = window.getSelection();
if(!sel.isCollapsed) {
var range = sel.getRangeAt(0);
sel.removeAllRanges();
document.designMode = "on";
sel.addRange(range);
document.execCommand("HiliteColor", false, "#ffffcc");
sel.removeAllRanges();
document.designMode = "off";
}
然后如何删除突出显示的颜色和还原文本?
How do I then remove the highlighted color and restore the text?
推荐答案
以下是添加和删除亮点的代码。实际上发布时间太长,所以我做了一个演示,并在下面贴了一个片段。这不是很理想,因为 unhighlight()
函数不会删除由highlight命令插入的< span>
元素,但有一点关心这将是一个可能的补充。
Here's some code to add and remove highlights. It's too long to post here practically, so I've made a demo and posted a snippet below. It's not quite ideal because the unhighlight()
function doesn't remove <span>
elements inserted by the highlight command, but with a little care this would be a possible addition.
现场演示: http://jsfiddle.net/timdown/Bvd9d/
代码段:
function unhighlight(node, colour) {
if (!(colour instanceof Colour)) {
colour = new Colour(colour);
}
if (node.nodeType == 1) {
var bg = node.style.backgroundColor;
if (bg && colour.equals(new Colour(bg))) {
node.style.backgroundColor = "";
}
}
var child = node.firstChild;
while (child) {
unhighlight(child, colour);
child = child.nextSibling;
}
}
这篇关于删除使用JavaScript添加到所选文本的高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文