使用 JavaScript 删除添加到所选文本的突出显示?
我使用 JavaScript 和以下代码突出显示了选定的文本:
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";
}
然后如何删除突出显示的颜色并恢复文本?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一些添加和删除突出显示的代码。实际上在这里发布太长了,所以我做了一个演示并在下面发布了一个片段。这不太理想,因为
unhighlight()
函数不会删除由突出显示命令插入的元素,但稍加小心,这将是一个可能的添加。
现场演示: http://jsfiddle.net/timdown/Bvd9d/
代码片段:
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.Live demo: http://jsfiddle.net/timdown/Bvd9d/
Code snippet:
您可以使用CSS代替:
编辑:更新以响应评论和澄清
尽管如此,这在某些浏览器(我认为是Firefox)中失败,其中元素样式更改为计算样式。
You could use CSS instead:
EDIT: Update in response to comment and clarification
Although, this fails in some browsers (I think it's Firefox) where the element style is changed to the computed style.
使用
Use