我希望在延迟后处理mouseover
事件,然后在页面刷新之前处于非活动状态。
到目前为止,这是我的代码:
$(function() {
$("#page-flip").mouseover(function() {
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
});
});
如何为此添加时间延迟,而不是在完全触发一次后使其无效?谢谢:)
答案 0 :(得分:3)
您可以使用.one()
让事件处理程序仅触发一次:
$(function() {
//bind a mouseover event handler that will fire only once
$("#page-flip").one('mouseover', function() {
//set a timeout so the code runs after half a second
setTimeout(function () {
//run your code here
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}, 500);
});
});
以下是演示:http://jsfiddle.net/jasper/fWakf/3/
您也可以使用.off()
:
$(function() {
$("#page-flip").on('mouseover', function() {
//remove this event handler so it doesn't fire in the future
$(this).off('mouseover');
setTimeout(function () {
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}, 500);
});
});
以下是演示:http://jsfiddle.net/jasper/fWakf/4/
请注意,.on()
是jQuery 1.7中的新增内容,在这种情况下是.bind()
。 .off()
也是新的,因此,如果您使用的是早于1.7和.bind()
,请使用.unbind()
。
答案 1 :(得分:0)
修改这个答案更糟而不是Jasper's。但它使用的模式不需要jQuery,所以我就把它留下了。
好吧,你可以简单地使用全局变量,或者复杂并完全删除事件。
简单的就像这样。
var __GlobalEventFired = false;
$(function() {
$("#page-flip").mouseover(function() {
if(!__GlobalEventFired)
{
__GlobalEventFired = true;
$(".box").toggleClass("box-change");
$(".films").toggleClass("films-change");
$(".synopsis").toggleClass("synopsis-change");
}
});
});