我有一个解决方案。在你的问题中没有足够的细节能够写出可以放入的东西,所以你可能需要调整它以得到你想要的东西。
这个想法是在突出显示代码正在运行时监视DOMNodeInserted
突变事件,并用className
标记插入的节点,然后可以使用它们查找并删除它们。 警告:突变事件已被弃用,但确实没有替代品,所以我正在使用我所拥有的。
Highlighter = (function() {
var highlighting = false;
document.addEventListener('DOMNodeInserted', function(e) {
if (highlighting) {
var target = e.target;
if (target.nodeType == 1) {
target.className = CLASS_NAME;
}
}
}, false);
var CLASS_NAME = 'highlighted';
return {
highlight: function(text, color) {
highlighting = true;
var sel = window.getSelection();
sel.collapse(document.body, 0);
if (window.find(text, true)) {
document.execCommand("hiliteColor", false, color);
sel.collapseToEnd();
}
highlighting = false;
},
unhighlight: function() {
var highlighted = document.querySelectorAll('.' + CLASS_NAME);
var i = highlighted.length;
while (i--) {
var node = highlighted[i];
node.parentNode.replaceChild(node.firstChild, node);
}
}
}
})();
仅适用于Chrome 17在这里测试工作的是一个小提琴:http://jsfiddle.net/LPJqW/
你针对一个特定的浏览器? Firefox可能? – Hemlock 2012-02-25 19:58:03
@Hemlock我只针对Chrome。 – Exception 2012-02-25 20:00:06
@Tim Down请帮助我。 – Exception 2012-02-25 21:36:28