javascript 事件觸發以後函式指定時間後再執行

admin發表於2017-03-28

本章節介紹一下如何觸發一個事件以後,函式延遲執行,下面就介紹一下如何實現此功能。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.main{
  width:500px;
  height:400px;
  border:dashed 1px #ccc;
  margin:0 auto;
  line-height:400px;
  text-align:center;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(function(){
  $(".main").mouseover(function(){
    setTimeout(function(){
      $(".main").html("螞蟻部落");
    },3000)
  });
})
</script>
</head>
<body>
<div class="main">原來的內容。</div>
</body>
</html>

上面的程式碼實現了我們的功能,其實並不是讓時間處理函式延遲執行,而是在事件處理函式內部再巢狀一個函式,使用定時器函式讓這個內部的函式延遲執行即可,setTimeout()函式可以參閱setTimeout()一章節。

相關文章