CSS3过渡(transition)允许元素在不同状态之间平滑地变化,而不是突然改变。当需要动态控制这些过渡效果时,jQuery的类操作方法提供了一种便捷的解决方案。
开发者经常遇到CSS过渡不生效的情况,常见原因包括:
通过jQuery添加/移除类来触发CSS过渡是最可靠的方法之一,因为:
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 100px;
height: 100px;
background: blue;
transition: all 0.5s ease;
}
.box.active {
width: 200px;
height: 200px;
background: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button id="toggleBtn">切换状态</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("#toggleBtn").click(function(){
$(".box").toggleClass("active");
});
});
</script>
</body>
</html>
setTimeout
或requestAnimationFrame
延迟类添加setTimeout
或requestAnimationFrame
延迟类添加这种方法结合了CSS3过渡的强大功能和jQuery操作DOM的便利性,是处理前端动画的常用模式。