Home > Web Front-end > JS Tutorial > How to Force a DOM Redraw in Chrome for Mac?

How to Force a DOM Redraw in Chrome for Mac?

Linda Hamilton
Release: 2024-11-29 07:26:10
Original
369 people have browsed it

How to Force a DOM Redraw in Chrome for Mac?

How to Force a DOM Redraw on Chrome for Mac

In web development, it's sometimes necessary to force the browser to redraw or refresh the DOM (Document Object Model). While there are various approaches that work in most browsers, Chrome for Mac poses a unique challenge.

The standard technique of modifying an unused CSS property, querying for an element dimension, and then reverting the change no longer works on Chrome for Mac. This behavior is due to optimizations that prevent redrawing when the offsetHeight property is retrieved.

To overcome this limitation, one can resort to a more invasive method:

    $(el).css("border", "solid 1px transparent");
    setTimeout(function() {
        $(el).css("border", "solid 0px transparent");
    }, 1000);
Copy after login

While this method ensures a redraw, it also causes a visible jump in the element's position, which can be undesirable. A more subtle approach that guarantees a redraw is:

$('#parentOfElementToBeRedrawn').hide().show(0);
Copy after login

This hides and then immediately shows the parent element, forcing a reflow. Alternatively, in plain JavaScript:

document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
Copy after login

For more fine-grained control over the redraw timing, a custom function can be defined:

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
}
Copy after login

The above is the detailed content of How to Force a DOM Redraw in Chrome for Mac?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template