2017-02-13 139 views
0

我正在使用jQuery处理当前正在使用的下拉菜单。我遇到了Timeout函数根本无法工作的问题。它的代码是:jQuery Timeout Function not working

$(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>

我试图做的是创造下拉的父悬停延迟。您需要将鼠标悬停在父级上方2秒钟才能显示下拉菜单。我也想将它与Slidedown和Slideup效果配对。

Slidedown和Slideup功能正常,但超时不起作用。

+5

再次,读取[文档】(https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout)总是有用.. 。 – Teemu

+0

这意味着你正在使用jQuery悬停方式错误..并且setTimeout属于JS .... – ymz

+3

jQuery的'.hover()'方法仅以1或2个函数作为参数。你给它4. https://api.jquery.com/hover/ – blex

回答

1

您不能只调用clearTimeout()(顺便说一下,它不是JQuery的一部分),您必须为它提供您想要取消的计时器的标识符。另外,setTimeout()clearTimeout()不是JQuery或JavaScript的组成部分。它们是由浏览器提供的window对象的方法。它们不是语言(JavaScript)或库(JQuery)的一部分。

此外,JQuery .hover() method需要两个参数,并且您提供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>

+2

查看@blex评论 – gaetanoM

+1

@gaetanoM更新后解决该问题。 –

+0

“但不知道你正在做什么”这是问题.. – gaetanoM