HOWTO · jQuery
在 jQuery 中使用 delay() 方法
本教程演示了如何使用 delay() 方法来延迟 jQuery 中特定项目的执行。
本页内容
jQuery 的 delay() 方法为执行下一项设置了一个计时器。本教程演示了如何在 jQuery 中使用 delay() 方法。
jQuery delay() 方法
delay() 是 jQuery 中的一个内置函数,用于延迟特定项目的执行。此方法是在排队的 jQuery 效果之间提供延迟的最佳选择。
此方法的语法是:
$(selector).delay(parameter1, parameter2);
其中,
selector可以是 id、类或元素名称。parameter1是延迟的速度,可以是毫秒,慢或快。parameter2可选地用于指定队列名称;默认值为fx,这是标准效果队列。
让我们尝试一些例子来展示 jQuery 中 delay() 方法的效果:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#box1").delay("slow").fadeIn();
$("#box2").delay("fast").fadeIn();
$("#box3").delay(1000).fadeIn();
$("#box4").delay(2000).fadeIn();
$("#box5").delay(3000).fadeIn();
$("#box6").delay(4000).fadeIn();
});
});
</script>
</head>
<body>
<h1>jQuery delay() method.</h1>
<p>Click the button to show the delay effect. Color boxes will fade in on the click with a delay</p>
<button>Click Here</button>
<br><br>
<div id="box1" style="width : 50px; height : 50px; display : none; background-color : pink;"> slow </div> <br>
<div id="box2" style="width : 50px; height : 50px; display : none; background-color : green;"> fast </div> <br>
<div id="box3" style="width : 50px; height : 50px; display : none; background-color : blue;"> 1 second </div> <br>
<div id="box4" style="width : 50px; height : 50px; display : none; background-color : violet;"> 2 seconds </div> <br>
<div id="box5" style="width : 50px; height : 50px; display : none; background-color : yellow;"> 3 seconds </div> <br>
<div id="box6" style="width : 50px; height : 50px; display : none; background-color : purple;"> 4 seconds </div> <br>
</body>
</html>
在上面的代码中,颜色框将以给定的延迟淡入。见输出:
让我们在 jQuery 中尝试另一个示例,它将基于 delay() 方法为 div 设置动画。请参阅示例:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$("#DemoButton").click(function() {
$("#DemoDiv").delay("fast").animate({
width: "250px",
padding: "35px"
});
$("#DemoDiv").delay("slow").animate({
width: "350px",
padding: "55px"
});
$("#DemoDiv").delay(1000).animate({
width: "275px",
padding: "50px"
});
$("#DemoDiv").delay(2000).animate({
width: "500px",
padding: "60px"
});
$("#DemoDiv").delay(3000).animate({
width: "200px",
padding: "40px"
});
});
});
</script>
<style>
#DemoDiv {
background-color : lightblue;
width : 200px;
height : 100px;
font-size : 30px;
padding : 10px;
display : block;
}
</style>
</head>
<body>
<div id="DemoDiv">Hello, This is Delftstack.com</div>
<button id="DemoButton">Click Here</button>
</body>
</html>
上面的代码将根据给定的时间延迟改变 div 的高度和宽度。见输出: