【问题标题】:jQuery Timeout Function not workingjQuery超时功能不起作用
【发布时间】:2022-04-19 16:05:31
【问题描述】:

我正在使用 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 效果配对。

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

【问题讨论】:

  • 再一次,阅读documentation 总是有用的......
  • 这意味着您使用jQuery的悬停方式错误..而setTimeout属于JS....
  • jQuery 的.hover() 方法只接受1 或2 个函数作为参数。你给它 4。api.jquery.com/hover
  • 你也可以提供一个HTML吗?
  • @ymz setTimeout() 不是 JavaScript 的一部分。它是宿主环境对象 (window) 的一种方法,但不是 ECMAScript 规范的一部分。

标签: javascript jquery html


【解决方案1】:

您不能只调用 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>

【讨论】:

  • 查看@blex 评论
  • @gaetanoM 已更新以解决该问题。
  • “但不知道你到底想做什么”这就是问题所在..
猜你喜欢
  • 2023-03-24
  • 2017-05-06
  • 2016-08-09
  • 2021-03-27
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
相关资源
最近更新 更多