Bre*_*ski 93 jquery events mouseevent settimeout
我想在jquery中延迟一个悬停事件.当用户将鼠标悬停在链接或标签上时,我正在读取文件.如果用户只是在屏幕上移动鼠标,我不希望立即发生此事件.有没有办法推迟事件的发射?
谢谢.
示例代码:
$(function() {
$('#container a').hover(function() {
$('<div id="fileinfo" />').load('ReadTextFileX.aspx',
{filename:'file.txt'},
function() {
$(this).appendTo('#info');
}
);
},
function() { $('#info').remove(); }
});
});
Run Code Online (Sandbox Code Playgroud)
更新: (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)
}
Run Code Online (Sandbox Code Playgroud)
Cre*_*esh 50
您需要在悬停时检查计时器.如果它不存在(即这是第一个悬停),请创建它.如果它存在(即这不是第一个悬停),请将其删除并重新启动它.将计时器有效负载设置为您的代码.
$(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
});
});
Run Code Online (Sandbox Code Playgroud)
我敢打赌jQuery有一个功能可以为你完成这一切.
编辑:啊,是的,jQuery插件救援
Mat*_*man 11
完全同意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);
}
});
Run Code Online (Sandbox Code Playgroud)
这个只是用于扩展<li>如果鼠标已经超过300毫秒.
归档时间: |
|
查看次数: |
90005 次 |
最近记录: |