javascript - jQuery 超时功能不起作用

标签 javascript jquery html

我正在使用 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>

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

向下滑动和向上滑动功能正常,但超时不起作用。

最佳答案

你不能只调用clearTimeout() (顺便说一句,它不是 JQuery 的一部分),您必须为其提供要取消的计时器的标识符。

此外,setTimeout()clearTimeout() 不是 JQuery 或 JavaScript 的一部分。它们是 window 对象的方法,由浏览器提供。它们不是语言 (JavaScript) 或库 (JQuery) 的一部分。

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

关于javascript - jQuery 超时功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42213392/

相关文章:

javascript - 用于在新窗口中打开 Google 表格副本的 Google Apps 脚本

javascript - 调整 Canvas 大小而不减少其宽度和高度(坐标)

javascript - 获取参数并将其存储并在变量上使用以在我的方法中使用

javascript - 如何在javascript中垂直显示数组表格

javascript - 将 "reference"保留到 React 状态变量

javascript - 我的 Flimsy AJAX 文件上传出了什么问题?

jquery - $(this) 和 jQuery 中的 this 有什么区别?

javascript - 在nodejs中一段时间​​后挂断http连接

jquery - 在 IE8 中扩展 div 不向下推内容

html - 在没有 flexbox 的情况下强制父元素没有定义高度的元素的最大高度?