Force DOM redraw/refresh on Chrome/Mac

前端 未结 24 2202
轻奢々
轻奢々 2020-11-22 02:11

Every once in a while, Chrome will render perfectly valid HTML/CSS incorrectly or not at all. Digging in through the DOM inspector is often enough to get it to realize the

24条回答
  •  执笔经年
    2020-11-22 03:14

    Not sure exactly what you're trying to achieve but this is a method I have used in the past with success to force the browser to redraw, maybe it will work for you.

    // in jquery
    $('#parentOfElementToBeRedrawn').hide().show(0);
    
    // in plain js
    document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
    document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
    

    If this simple redraw doesn't work you can try this one. It inserts an empty text node into the element which guarantees a redraw.

    var forceRedraw = function(element){
    
        if (!element) { return; }
    
        var n = document.createTextNode(' ');
        var disp = element.style.display;  // don't worry about previous display style
    
        element.appendChild(n);
        element.style.display = 'none';
    
        setTimeout(function(){
            element.style.display = disp;
            n.parentNode.removeChild(n);
        },20); // you can play with this timeout to make it as short as possible
    }
    

    EDIT: In response to Šime Vidas what we are achieving here would be a forced reflow. You can find out more from the master himself http://paulirish.com/2011/dom-html5-css3-performance/

提交回复
热议问题