延迟jQuery的hover事件?

我想推迟在jQuery中的hover事件。 当用户hover在链接或标签上时,我正在从文件中读取数据。 如果用户只是在屏幕上移动鼠标,我不希望这个事件立即发生。 有没有办法延迟事件发生?

谢谢。

示例代码:

$(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) } 

使用jQuery的hoverIntent插件: http ://cherne.net/brian/resources/jquery.hoverIntent.html

对于你所描述的内容来说,这绝对是完美的,而且我几乎在每个需要鼠标hover的菜单等项目上都使用它。

这个方法有一个问题,一些接口没有“hover”状态,例如。 移动浏览器,如iphone上的safari。 您可能隐藏了界面或导航的重要部分,无法在此类设备上打开它。 你可以用设备特定的CSS来解决这个问题。

你需要检查一个计时器hover。 如果它不存在(即这是第一个hover),创build它。 如果它存在(即这不是第一个hover),杀死它并重新启动它。 将计时器有效负载设置为您的代码。

 $(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有一个function,它包装了这一切为你。

编辑 :啊,是的, jQuery插件来救援

完全同意hoverIntent是最好的解决scheme,但是如果你恰巧是一个在网站上工作的不幸的人,为了批准jQuery插件,这里是一个快速和肮脏的解决scheme,对我来说效果很好:

 $('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); } }); 

如果鼠标已经超过300毫秒,这只是扩展一个<li>。

您可以在mouseout事件中使用setTimeout()调用和clearTimeout()。

在2016年,Crescent Fresh的解决scheme没有像我预期的那样工作,所以我想出了这个:

 $(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; }); 

我的解决scheme很简单。 延迟打开菜单,如果用户保持鼠标在超过300毫秒obj:

 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); });