動態修改樣式、類名、內容後,瀏覽器有時不會立即重繪,導致視覺異常(如 transform 動畫不生效、滾動條不更新)。強制觸發重繪可解決。
jQuery.fn.redraw = function(){
return this.each(function(){
this.style.display = 'none';
this.offsetHeight; // 讀取佈局屬性強制回流
this.style.display = 'block';
});
};
$("#myElement").addClass("new-class").redraw();
// 或
$(".animated").redraw();
display: none 讓元素脫離渲染樹。offsetHeight(或 offsetWidth, getComputedStyle)強制瀏覽器計算佈局(Reflow)。display: block 恢復顯示,瀏覽器重新繪製(Repaint)。// 方案 1:請求動畫幀
requestAnimationFrame(function(){ element.style.transform = 'translateZ(0)'; });
// 方案 2:觸發回流的常用屬性讀取
element.offsetHeight; // 或 element.clientHeight, getComputedStyle(element).height
頻繁強制重繪會影響性能,僅在必要時使用(如 CSS 動畫啟動前、滾動容器尺寸變更後)。