如何强制 WebKit 重绘/重绘以传播样式更改? [英] How can I force WebKit to redraw/repaint to propagate style changes?

查看:58
本文介绍了如何强制 WebKit 重绘/重绘以传播样式更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的 JavaScript 来实现样式更改:

I have some trivial JavaScript to effect a style change:

sel = document.getElementById('my_id');
sel.className = sel.className.replace(/item-[1-9]-selected/,'item-1-selected');
return false;

这适用于最新版本的 FF、Opera 和 IE,但不适用于最新版本的 Chrome 和 Safari.

This works fine with the latest versions of FF, Opera and IE, but fails on the latest versions of Chrome and Safari.

它影响两个后代,它们恰好是兄弟姐妹.第一个兄弟更新,但第二个没有.第二个元素的子元素也有焦点并包含 标记,该标记在 onclick 属性中包含上述代码.

It affects two descendants, which happen to be siblings. The first sibling updates, but the second doesn’t. A child of the second element also has focus and contains the <a> tag that contains the above code in an onclick attribute.

在 Chrome 的开发者工具"窗口中,如果我轻推(例如取消选中和选中)any 元素的 any 属性,第二个兄弟元素将更新为正确的样式.

In the Chrome "Developer Tools" window if I nudge (e.g. uncheck & check) any attribute of any element, the second sibling updates to the correct style.

是否有一种解决方法可以轻松地以编程方式推动"WebKit 做正确的事情?

Is there a workaround to easily and programmatically "nudge" WebKit into doing the right thing?

推荐答案

我发现了一些复杂的建议和许多没有用的简单建议,但是 Vasil Dinkov 提供了一个简单的解决方案来强制重绘/重绘,效果很好:

I found some complicated suggestions and many simple ones that didn’t work, but a comment to one of them by Vasil Dinkov provided a simple solution to force a redraw/repaint that works just fine:

sel.style.display='none';
sel.offsetHeight; // no need to store this anywhere, the reference is enough
sel.style.display='';

如果它适用于块"以外的样式,我会让其他人评论.

I’ll let someone else comment if it works for styles other than "block".

谢谢,瓦西尔!

这篇关于如何强制 WebKit 重绘/重绘以传播样式更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆