jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。jQuery 的 stop()
方法用于停止当前正在运行的动画,并清除动画队列。
stop()
方法有两种形式:
$(selector).stop([clearQueue], [jumpToEnd])
clearQueue
:布尔值,表示是否清除动画队列,默认为 false
。jumpToEnd
:布尔值,表示是否立即完成当前动画,默认为 false
。当用户需要停止某个元素的滚动动画时,可以使用 stop()
方法。例如,在一个轮播图中,用户点击暂停按钮时,可以使用 stop()
方法停止图片的滚动动画。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Stop Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#scroll {
width: 200px;
height: 200px;
overflow: auto;
border: 1px solid black;
}
#content {
width: 400px;
height: 800px;
background-color: lightgray;
}
</style>
</head>
<body>
<div id="scroll">
<div id="content"></div>
</div>
<button id="stopScroll">Stop Scroll</button>
<script>
$(document).ready(function() {
// 自动滚动
var interval = setInterval(function() {
$('#scroll').animate({ scrollTop: $('#scroll')[0].scrollHeight }, 1000);
}, 2000);
// 停止滚动
$('#stopScroll').click(function() {
$('#scroll').stop(true, true);
clearInterval(interval);
});
});
</script>
</body>
</html>
问题:为什么 stop()
方法没有停止动画?
原因:
clearQueue
参数为 true
,动画队列中的其他动画仍然会继续执行。jumpToEnd
参数未设置为 true
,当前动画不会立即停止,而是会继续执行到结束。解决方法:
stop()
方法时设置 clearQueue
和 jumpToEnd
参数为 true
。stop()
方法之前,动画已经开始执行。$('#scroll').stop(true, true);
通过以上方法,可以确保 stop()
方法能够正确停止动画并清除动画队列。
领取专属 10元无门槛券
手把手带您无忧上云