我试图在后台运行一些 javascript 时更改元素的样式,以指示页面“繁忙”或“正在加载”。我一直在尝试通过使用 jQuery 的 .toggleClass()
在 JS 脚本的开头打开一个类,并在最后关闭它,并附加一些合适的 CSS 样式来实现此目的类。
尽管该类会立即切换,但附加到它的 CSS 样式要等到 JS 执行完毕后才会应用。因此,如果该类同时打开和关闭,用户不会看到样式有任何变化。
我在下面提供了一个简单的示例。如何在执行其余 JS 代码之前强制立即应用 CSS 样式的更改?
$(function() {
$('#box').click(function() {
// Toggle class 'red' on.
$(this).toggleClass('red');
// Do something that takes time.
for (i = 0; i < 10000; i++) {
console.log(i);
}
// Toggle class 'red' off.
$(this).toggleClass('red');
});
});
.wrapper {
margin: 15px;
text-align: center;
color: #000;
}
#box {
margin: 15px 0;
width: 100px;
height: 100px;
line-height: 100px;
cursor: pointer;
background: #ccc;
border: solid 3px #ccc;
-webkit-transition: all .3s linear 0s;
transition: all .3s linear 0s;
}
#box.red {
background: #f43059;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div id="box">Click me.</div>
</div>
最佳答案
问题是您的“需要时间的东西”是同步且阻塞的 - 当它运行时,浏览器重画将被禁用。
一种选择是监听 transitionend
事件,以确保在资源密集型操作运行之前完成红色动画。
为了使 .red
动画的删除也正确,您可以在繁重的操作完成后立即设置 setTimeout
。请注意,如果您使用 addClass
和 removeClass
而不是 toggleClass
,您的代码会更清晰:
$('#box').click(function() {
$(this).one('transitionend', () => {
// Do something that takes time.
for (i = 0; i < 1000; i++) {
console.log(i);
}
// Toggle class 'red' off.
setTimeout(() => {
$(this).removeClass('red');
});
});
$(this).addClass('red');
});
.wrapper {
margin: 15px;
text-align: center;
color: #000;
}
#box {
margin: 15px 0;
width: 100px;
height: 100px;
line-height: 100px;
cursor: pointer;
background: #ccc;
border: solid 3px #ccc;
-webkit-transition: all .3s linear 0s;
transition: all .3s linear 0s;
}
#box.red {
background: #f43059;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div id="box">Click me.</div>
</div>
关于javascript - 当使用 jQuery 切换类时 CSS 样式不会立即应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53992871/