gpt4 book ai didi

javascript - 类在风格之前改变

转载 作者:行者123 更新时间:2023-11-30 14:59:24 25 4
gpt4 key购买 nike

请参阅以下代码段:

$('div').click(function(){
$(this).css('width', '10px').addClass('wide');
});
div {width: 100px; height: 100px; background-color: green;}
div.wide {width: 200px !important; transition: width 2s;}
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

我希望首先应用样式,使其宽 10 像素,然后添加类使其扩展到 200 像素。然而事实并非如此。如果您查看检查器,您可以看到类属性在样式属性之前被更改。为什么会这样,我怎样才能让它以正确的方式工作?

谢谢!

最佳答案

在添加类(class)之前尝试稍等片刻,您永远看不到两者之间的时间差异您的计算机太快了。

最后,这是一个更多关于 javascript 是异步的方式并且不在每个命令之间呈现 DOM 的问题。将超时设置在那里告诉 javascript 它现在可以做其他事情并将上下文切换到渲染。

$('div').click(function(){
$(this).css('width', '10px');
var smallBox = this;
setTimeout(function(){
$(smallBox).addClass('wide');
}, 0);
});
div {width: 100px; height: 100px; background-color: green;}
div.wide {width: 200px !important; transition: width 2s;}
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

关于javascript - 类在风格之前改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46762506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com