簡體   English   中英

jQuery的超時功能無法正常工作

[英]jQuery Timeout Function not working

我正在使用jQuery在下拉菜單中進行當前工作。 我遇到了超時功能根本無法工作的問題。 它的代碼是:

 $(document).ready(function() { $('.has-sub').hover( function() { $('ul', this).stop(true, true).slideDown(500); }, function() { $('ul', this).stop(true, true).slideUp(400); }, function() { setTimeout(function() { $('.has-sub').addClass("tap"); }, 2000); }, function() { $(this).removeClass("tap"); clearTimeout(); } ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 

我想做的是為Dropdown的父級創建一個懸停延遲。 您需要將鼠標懸停在父控件上2秒鍾,以顯示下拉菜單。 我還想將其與Slidedown和Slideup效果配對。

向下滑動和向上滑動功能正常,但是超時不起作用。

您不能只調用clearTimeout() (順便說一句,它不是JQuery的一部分),您必須為其提供要取消的計時器的標識符。

此外, setTimeout()clearTimeout()不為此事的JQuery的一部分或JavaScript。 它們是window對象的方法,由瀏覽器提供。 他們不是語言(JavaScript的)或庫(JQuery的)的一部分。

此外, JQuery的.hover()方法需要兩個參數,並且您提供4.我在下面將它們結合在一起,但不知道正是你正在嘗試做的,你可能需要調整。

 $(document).ready(function() { // This will represent the unique ID of the timer // It must be declared in a scope that is accessible // to any code that will use it var timerID = null; $('.has-sub').hover( function() { // Clear any previously running timers, so // we dont' wind up with multiples. If there aren't // any, this code will do noting. clearTimeout(timerID); $('ul', this).stop(true, true).slideDown(500); // Set the ID variable to the integer ID returned // by setTimeout() timerID = setTimeout(function() { $('.has-sub').addClass("tap"); }, 2000); }, function() { $('ul', this).stop(true, true).slideUp(400); $(this).removeClass("tap"); // Clear the particular timer based on its ID clearTimeout(timerID); } ); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM