用setTimeOut()和delay()来实现延时案例,给定一个div元素,如何使用jQuery几秒后隐藏div元素?
想要使用jQuery延迟几秒隐藏div元素,可以先选择div元素,然后使用延迟函数(setTimeOut(), delay())来提供隐藏div元素的延迟。
示例1:使用setTimeOut()方法为fadeOut()方法提供延迟
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<style>
#div {
background: lightcoral;
height: 100px;
width: 200px;
line-height: 100px;
margin: 0 auto;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<p style="font-size: 19px; font-weight: bold;">
单击按钮,在1秒后隐藏DIV元素。
</p>
<div id="div"> 一个DIV盒子 </div>
<br>
<button onClick="Fun()">点击这里</button>
<p id="DOWN" style="color: lightcoral; font-size: 24px; font-weight: bold;"></p>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
function Fun() {
setTimeout(function() {
$("#div").fadeOut('fast');
}, 1000);
$("#DOWN").text("DIV元素在1秒后隐藏");
}
</script>
</body>
</html>示例2:使用delay()方法为fadeOut()方法提供延迟
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<style>
#div {
background: lightcoral;
height: 100px;
width: 200px;
line-height: 100px;
margin: 0 auto;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<p style="font-size: 19px; font-weight: bold;">
单击按钮,在2秒后隐藏DIV元素。
</p>
<div id="div"> 一个DIV盒子 </div>
<br>
<button onClick="Fun()">点击这里</button>
<p id="DOWN" style="color: lightcoral; font-size: 24px; font-weight: bold;"></p>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
function Fun() {
$("#div").delay(2000).fadeOut('fast');
$("#DOWN").text("DIV元素在2秒后隐藏");
}
</script>
</body>
</html> 


网友评论文明上网理性发言 已有0人参与
发表评论: