在用户将鼠标悬停在链接上2秒钟后使函数执行 [英] Make function execute after user hovers over link for 2 seconds

查看:70
本文介绍了在用户将鼠标悬停在链接上2秒钟后使函数执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是的,我知道之前曾有人问过这个问题,但我找不到有效的答案.这是其他问题之一的公认答案:

Yes, I know this question has been asked before, but I can't find an answer that works. This is an accepted answer from one of the other questions:

$('#element').hover(function()
{
    $(this).data('timeout', window.setTimeout(function()
    {
        alert('hovered for 2 seconds');
    }, 2000));
},
function()
{
    clearTimeout($(this).data('timeout'));
    alert('mouse left');
});

http://jsfiddle.net/nCcxt/

如您所见,它并没有达到预期的效果.

As you see it doesn't do what it's supposed to.

我需要的理论上很简单,但是我无法使它正常工作-当用户将鼠标悬停在链接上2秒钟时,将调用一个函数.如果用户在两秒钟之前将鼠标移开,则什么也不会发生.

What I need is simple in theory but I can't get it to work - when a user hovers over a link for 2 seconds, a function is called. If the user moves the mouse away before 2 seconds pass, nothing happens.

推荐答案

代码可以正常运行.它只会由于alert()调用而中断,从而导致触发mouseout事件.

The code works perfectly fine. It only breaks due to the alert() calls which causes the mouseout event to be triggered.

我们从中学到什么? 请勿将alert()与焦点/悬停/移动相关的事件结合使用.

What do we learn from it? Do not use alert() in combination with focus/hover/mousemove-related events.

顺便说一句,已经有jQuery插件可用于您要执行的操作: http://cherne. net/brian/resources/jquery.hoverIntent.html

By the way, there are already jQuery plugins available for what you want to do: http://cherne.net/brian/resources/jquery.hoverIntent.html

这篇关于在用户将鼠标悬停在链接上2秒钟后使函数执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆