延迟jquery悬停事件?
-
22-07-2019 - |
题
我想延迟 jquery 中的悬停事件。当用户将鼠标悬停在链接或标签上时,我正在读取文件。我不希望在用户只是在屏幕上移动鼠标时立即发生此事件。有没有办法延迟事件的触发?
谢谢。
示例代码:
$(function() {
$('#container a').hover(function() {
$('<div id="fileinfo" />').load('ReadTextFileX.aspx',
{filename:'file.txt'},
function() {
$(this).appendTo('#info');
}
);
},
function() { $('#info').remove(); }
});
});
更新: (1/14/09)添加HoverIntent插件后,将上面的代码更改为以下代码来实现它。实施起来非常简单。
$(function() {
hiConfig = {
sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
interval: 200, // number = milliseconds for onMouseOver polling interval
timeout: 200, // number = milliseconds delay before onMouseOut
over: function() {
$('<div id="fileinfo" />').load('ReadTextFileX.aspx', {filename:'file.txt'},
function() {
$(this).appendTo('#info');
}
);
}, // function = onMouseOver callback (REQUIRED)
out: function() { $('#info').remove(); } // function = onMouseOut callback (REQUIRED)
}
$('#container a').hoverIntent(hiConfig)
}
解决方案
使用hoverIntent jQuery插件: http://cherne.net/brian/resources /jquery.hoverIntent.html
这是对你的描述绝对完美的,我已经用它在几乎所需的菜单等的鼠标悬停激活每一个项目......
有一个疑难杂症该方法,一些接口是没有一个“悬停”状态例如。移动浏览器像在iPhone上的Safari。你可能会隐藏接口或导航的重要组成部分,没有办法打开它在此类设备上。你可以避开这个问题与设备特定CSS。
其他提示
您需要检查悬停定时器。如果它不存在(即这是第一个悬停),创建它。如果存在的话(即,这是不的第一悬停),杀死它和重新启动它。定时器有效载荷设置为您的代码。
$(function() {
var timer;
$('#container a').hover(function() {
if(timer) {
clearTimeout(timer);
timer = null
}
timer = setTimeout(function() {
$('<div id="fileinfo" />').load('ReadTextFileX.aspx',
{filename:'file.txt'},
function() {
$(this).appendTo('#info');
}
);
}, 500)
},
// mouse out
});
});
我敢打赌,jQuery有一个包装这一切都为你的函数。
修改的:是啊, jQuery插件救援一>
完全同意hoverIntent是最好的解决方案,但如果你碰巧是一个不幸的草包,在一个网站上工作,需要一个漫长而漫长的过程来批准jQuery插件,这里有一个快速但肮脏的解决方案,对我来说效果很好:
$('li.contracted').hover(function () {
var expanding = $(this);
var timer = window.setTimeout(function () {
expanding.data('timerid', null);
... do stuff
}, 300);
//store ID of newly created timer in DOM object
expanding.data('timerid', timer);
}, function () {
var timerid = $(this).data('timerid');
if (timerid != null) {
//mouse out, didn't timeout. Kill previously started timer
window.clearTimeout(timerid);
}
});
这个只是为了当鼠标停留在 <li> 上的时间超过 300 毫秒时扩展 <li>。
您可以使用的setTimeout()与clearTimeout调用()上mouseout事件。
在2016年之前,预期为我新月新鲜的解决方案没有工作,所以我想出了这个:
$(selector).hover(function() {
hovered = true;
setTimeout(function() {
if(hovered) {
//do stuff
}
}, 300); //you can pass references as 3rd, 4th etc. arguments after the delay
}, function() {
hovered = false;
});
我的解决办法是容易的。延迟打开菜单如果用户在300毫秒上物镜保持的mouseenter:
var sleep = 0;
$('#category li').mouseenter(function() {
sleep = 1;
$('#category li').mouseleave(function() {
sleep = 0;
});
var ob = $(this);
setTimeout(function() {
if(sleep) {
// [...] Example:
$('#'+ob.attr('rel')).show();
}
}, 300);
});