WebKit Redraw Enigmatic Behavior: Resolving Style Changes
In the realm of web development, ensuring consistent appearance across browsers can pose challenges. One such issue arises when attempting to apply style changes using JavaScript in WebKit-based browsers (e.g., Chrome, Safari).
Consider the following JavaScript code:
sel = document.getElementById('my_id'); sel.className = sel.className.replace(/item-[1-9]-selected/,'item-1-selected'); return false;
This code aims to modify the class attribute of an element with the ID "my_id". However, in WebKit browsers, only the first affected descendant sibling element updates, while the second remains unchanged, even though they are immediate siblings of the modified element.
Intriguingly, in Chrome's "Developer Tools," simply toggling any attribute of any element triggers the correct rendering of the second sibling. This suggests that WebKit requires a "nudge" to propagate style changes.
Trivial Yet Effective Solution
After exploring various ineffective recommendations, a simple and elegant solution emerged in a comment by Vasil Dinkov. To force a repaint in WebKit, execute the following:
sel.style.display='none'; sel.offsetHeight; // Reference is sufficient, no need to store the value sel.style.display='';
This technique hides the element ("sel"), reads its offsetHeight (a property non-zero for non-hidden elements), and then unhides the element. This subtle manipulation triggers a redraw, propagating the intended style changes.
Additional Considerations
It remains to be tested whether this solution applies to style changes beyond the "block" property. However, for the author's situation, it provided a straightforward and effective solution. By eliminating the inconsistency in style propagation, it ensures a visually consistent webpage across WebKit-based browsers.
The above is the detailed content of Why Do WebKit Browsers Need a 'Nudge' to Propagate Style Changes Made via JavaScript?. For more information, please follow other related articles on the PHP Chinese website!