功能前延迟,悬停时取消功能
delay before function and cancel function on hover out
我正在尝试达到以下目的。我想在将鼠标悬停在菜单上超过 3 秒后折叠菜单。但是当我在 3 秒之前将鼠标悬停在菜单之外时,它一定不能崩溃。
$("#sidebar").hover(function() {
if($(this).hasClass("collapsed-by-user")) {
setTimeout(sidebarCollapse, 3000);
}
}, function() {
if($(this).hasClass("collapsed-by-user")) {
sidebarNotCollapse();
preventDefault();
}
});
这就是我到目前为止得到的。3 秒后崩溃正在工作,但如果我在 3 秒前悬停,它仍然会崩溃。
知道怎么做吗?
您需要记住计时器句柄,并在悬停结束时(如果在 3 秒内)与clearTimeout
一起使用:
var handle = 0;
var when = 0;
$("#sidebar").hover(function() {
// Start the timer if we don't have it running already and we have the class
if(!handle && $(this).hasClass("collapsed-by-user")) {
handle = setTimeout(function() {
handle = 0;
sidebarCollapse();
}, 3000);
when = Date.now(); // Remember when it started
}
}, function() {
// If we have a handle and it's been less than three seconds,
// stop the timeout from running by clearing it
if (handle && Date.now() - when < 3000) {
clearTimeout(handle);
}
// Reset our handle var regardless (for next time)
handle = 0;
});
请注意,当计时器在 callilng sidebarCollapse
之前触发时,我们将清除handle
。
(我不确定你为什么要做那个类检查,所以我把它留了下来。
或者根据Jamiec下面的评论进行更新; 他是对的,我们真的不需要这样做when
检查:
var handle = 0;
$("#sidebar").hover(function() {
// Start the timer if we don't have it running already and we have the class
if(!handle && $(this).hasClass("collapsed-by-user")) {
handle = setTimeout(function() {
handle = 0;
sidebarCollapse();
}, 3000);
}
}, function() {
// clearTimeout is a no-op if the timer's already fired
clearTimeout(handle);
handle = 0;
});
相关文章:
- Bootbox:取消对话框后的回调功能/点击'X'按钮
- 如何在具有分页功能的表格排序器中取消选中所有复选框
- 暂停和取消暂停功能中的音频
- 取消/停止超时功能
- Javascript提示取消终止功能
- 多功能 javascript 停止其他如果警报取消
- 将 JavaScript 与 TreeView 节点一起使用 检查/取消选中功能
- 复选框 - 选中取消选中功能不起作用
- 在 RXJS 中的订阅功能块中处置/取消订阅
- 确认框取消功能与确定执行相同的操作
- 功能前延迟,悬停时取消功能
- 取消选中功能不起作用
- 如何在 javascript 中取消打印功能后重新加载脚本
- 反转静音/取消静音功能这个特殊的html5视频播放器
- 单击功能时取消选中其他单选按钮
- AngularJS输入检查/取消检查有2个功能
- 如何使用AngularJS实现粗体-取消粗体功能
- 鼠标向上时取消功能
- 什么功能/事件由“;取消“;leaflet.draw中的按钮
- 取消isdirty功能的绑定