简体   繁体   中英

How to remove backcolor of window.find Highlights

How to roll back highlights which are caused with the below code

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(); 
     }
}

How to remove all highlights backcolor, ie "YellowGreen". I have seen a post that is related to my question. But the accepted answer is not working. Please somebody look into it and help me.

I have a solution. There isn't really enough detail in your question to be able to write something that can drop in, so you'll probably have to tweak it to get what you want.

The idea is to monitor the DOMNodeInserted mutation event while the highlight code is running and mark the nodes being inserted with a className that can then be used to find and remove them. Caveat : mutation events are deprecated, but there really isn't a replacement so I'm using what I have.

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);
            }
        }
    }
})();

​Tested only in Chrome 17. Here is a fiddle of it working: http://jsfiddle.net/LPJqW/

I found an alternative for this....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM