延迟JavaScript悬停操作

9
我网站上有一张图片,它附带了jquery悬停动作。但很容易意外悬停在那个区域上,如果你这样做了不止一次,悬停就会不断出现、消失、出现等,直到它为每次悬停都显示和消失一次。有没有办法让动作只有在悬停几秒钟后才触发呢?我不想只是延迟动作,因为它仍然会在每次悬停时发生,我想知道是否有一种方法可以让悬停只有在你停留在图片上几秒钟后才算。

目前的脚本:

$("img.badge").hover(
function() {
  $("h3.better").animate({"left": "125px"}, 1200);
},
function() {
  $("h3.better").animate({"left": "-500px"}, 800);
});
3个回答

13
你可以使用setTimeout来启动动作,并在mouseout事件上绑定一个调用clearTimeout的函数:
$('img.badge').hover(function(){
    window.mytimeout = setTimeout(function(){
        $("h3.better").animate({"left": "125px"}, 1200);
    }, 2000);
}, function(){
    clearTimeout(window.mytimeout);    
});

或者你可以使用一个插件来达到这个效果,比如像 hoverintent


听起来这个方案非常完美。我还在学习JavaScript,不确定如何实现那段代码。你能给我演示一下吗? - Molly Campbell
@MollyCampbell 我详细说明了无插件解决方案。如果您打算使用插件,我会让您查看他们的文档。 - Denys Séguret

1
在执行动画之前使用.stop()来取消先前的动画。我相信这是您正在寻找的,可以解决您当前的问题。
$("img.badge").hover(
function() {
  $("h3.better").stop().animate({"left": "125px"}, 1200);
},
function() {
  $("h3.better").stop().animate({"left": "-500px"}, 800);
});

0
你可以使用定时器来延迟触发悬停行为,直到悬停了一定的时间。如果在定时器触发之前悬停已经结束,则清除定时器,以免只有短暂悬停时触发了操作。
$("img.badge").hover(function() {
    var timer = $(this).data("hover");
    // if no timer set, set one otherwise if timer is already set, do nothing
    if (!timer) {
        // set timer that will fire the hover action after 2 seconds
        timer = setTimeout(function() {
            $("h3.better").stop(true).animate({"left": "125px"}, 1200);
            $(this).data("hover", null);
        }, 2000);
        // save timer
        $(this).data("hover", timer);
    }
}, function() {
    var timer = $(this).data("hover");
    if (timer) {
        clearTimeout(timer);
        $(this).data("hover", null);
    } else {
        // probably would be better to make this an absolute position rather
        // than a relative position
        $("h3.better").stop(true).animate({"left": "-500px"}, 800);
    }
});

注意:我还向您的动画中添加了.stop(true),因此动画永远不会堆积。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接