Home >Web Front-end >JS Tutorial >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);
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);
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';
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 }
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!