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