使用 jquery 添加/删除类,但元素不会重新绘制以反映
我有两个元素(想象一下并排的两个按钮)。我动态切换“focusd”类来更改突出显示的效果。然而,有一个怪癖,它并不总是被重绘和/或插入到 DOM 中。例如,如果在 chrome 中我执行 console.log,我会看到类更改(我在 jquery 中使用removeClass/addClass)。但是,如果我转到检查器中的“元素”选项卡,它会显示之前的类(事实上,我没有看到反映类切换的重绘。)
我尝试将父 div 设置为不显示,然后返回到阻止但这不起作用。这是一个“一次性”模式屏幕,因此效率并不重要,因此我采用了这种技巧,我基本上复制了父级的innerhtml,删除并重新插入该元素。可怕!
// Not sure why I need this hack. But if I don't, the buttons don't seem to get redrawn
var htm = jQuery(".rdata_container").html(); // copy the innerhtml
jQuery(".rdata_container").empty(); // empty and then append back
jQuery(".rdata_container").append(htm);
这似乎是一个特定的怪癖,一定有人遇到过(我希望)。如果是这样,我很想知道为什么我的更改没有得到反映。
编辑 代码发布在这里: http://jsfiddle.net/roblevintennis/JCZnf/
I have two elements (think of two buttons side by side). I dynamically toggle the class "focusd" to change the highlighted effect. However, there's a quirk it doesn't always get redrawn and/or inserted in the DOM. For example, if in chrome I do console.log, I see the class changes (I'm using removeClass/addClass in jquery). But if I go to the Elements tab in the inspector, it shows the classes from before (and in fact, I'm not seeing the redrawing reflecting the toggling of the classes.)
I tried setting the parent div to display none then back to block but that didn't work. It's a "one off" modale screen, so efficiency doesn't matter so I've resorted to this hack where I essentially copy the parent's innerhtml, remove and reinsert the element. Horrible!
// Not sure why I need this hack. But if I don't, the buttons don't seem to get redrawn
var htm = jQuery(".rdata_container").html(); // copy the innerhtml
jQuery(".rdata_container").empty(); // empty and then append back
jQuery(".rdata_container").append(htm);
This seems like a specific quirk that someone must have ran into (I hope). If so, I'd love to know why my changes aren't reflected.
EDIT
Code posted here:
http://jsfiddle.net/roblevintennis/JCZnf/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你对元素进行其他操作时,你可以使用 setTimeout ,例如:
或者你可以像这样强制重绘:
这些技巧将强制浏览器重新绘制更改,因为有这里发生了两件事,浏览器逻辑只是将它们合二为一,这不是所需的行为。
you can use
setTimeout
when you are doing the other operation on the element, so for example:Or you could force a repaint like so:
These tricks will force the browser to re-draw the change, because there are two things happening here and the browser logic just combines them into one, which isn't the desired behavior.
不能直接回答您的问题,但您可以使用jQuery 的toggleClass 函数 来简化您的代码。
这是使用toggleClass() 和 jQuery 1.6 的更新版本,并且 AFAICT 工作正常。
http://jsfiddle.net/JCZnf/7/
Not directly an answer to your question, but you can use jQuery's toggleClass function to simplify your code.
Here's an updated version that uses toggleClass() and jQuery 1.6 and AFAICT works fine.
http://jsfiddle.net/JCZnf/7/