给定一个 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>
效果图:
示例 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>
效果图:
来源: http://www.css88.com/qa/jquery/10419.html