如何使用jQuery延迟几秒隐藏div元素?

给定一个div元素,如何使用jQuery几秒后隐藏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>

效果图:

1.gif

示例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>

效果图:

2.gif

以上就是如何使用jQuery延迟几秒隐藏div元素?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » jQuery 答疑