jQuery动画默认是队列化的,这意味着如果你连续调用多个动画方法,它们会按顺序执行。这种设计有时很有用,但有时我们需要让多个动画同时运行。
jQuery使用一个称为"fx"的队列来管理动画。当你调用.animate()
或其他动画方法时,jQuery会将动画添加到这个队列中,然后依次执行。
queue: false
选项$('#element1').animate({left: '100px'}, {queue: false});
$('#element2').animate({top: '100px'}, {queue: false});
.stop()
清除队列$('#element1').stop(true, true).animate({left: '100px'});
$('#element2').stop(true, true).animate({top: '100px'});
$('#element1').css('transition', 'left 1s').css('left', '100px');
$('#element2').css('transition', 'top 1s').css('top', '100px');
$.when()
$.when(
$('#element1').animate({left: '100px'}, {queue: false}).promise(),
$('#element2').animate({top: '100px'}, {queue: false}).promise()
).done(function() {
console.log('Both animations completed');
});
queue: false
时,动画不会添加到jQuery队列中,因此无法使用.stop()
等方法控制<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 50px;
height: 50px;
background: red;
position: absolute;
}
#box1 { left: 0; top: 0; }
#box2 { left: 0; top: 100px; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<script>
$(document).ready(function() {
// 两个盒子将同时移动
$('#box1').animate({left: '200px'}, {queue: false, duration: 1000});
$('#box2').animate({left: '200px'}, {queue: false, duration: 1500});
});
</script>
</body>
</html>
通过以上方法,你可以有效地让jQuery动画同时运行,而不是顺序执行。
没有搜到相关的文章