【问题标题】:How to remove backcolor of window.find Highlights如何去除 window.find Highlights 的背景色
【发布时间】:2012-03-02 16:15:00
【问题描述】:

如何回滚由以下代码引起的高光

if (window.find && window.getSelection) {
     var sel = window.getSelection(); 
     sel.collapse(document.body, 0);  
     document.body.offsetHeight;
     if (window.find(text, true)) { 
        document.execCommand("hiliteColor", false, "YellowGreen"); 
        sel.collapseToEnd(); 
     }
}

如何去除所有高光背景色,即“黄绿色”。我看到了与我的问题相关的post。但是接受的答案不起作用。请有人调查一下并帮助我。

【问题讨论】:

  • 您的目标是特定浏览器吗?也许是火狐?
  • @Hemlock 我只针对 Chrome。
  • @Tim Down 请帮帮我。

标签: javascript google-chrome


【解决方案1】:

我有一个解决方案。您的问题中没有足够的细节来编写可以插入的内容,因此您可能必须对其进行调整以获得您想要的内容。

这个想法是在高亮代码运行时监视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/

【讨论】:

    【解决方案2】:

    我找到了一个替代方案....

    $('body *').each(function () {
      ($(this).css('background-color') == "rgb(70, 130, 180)") || ($(this).css('background-color') == "rgb(255, 192, 203)") ? $(this).css("background-color", "") : 0;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多