如果鼠标超过div,则取消setTimeout [英] Cancel setTimeout if mouse is over div

查看:108
本文介绍了如果鼠标超过div,则取消setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div类,比如A和B.当鼠标超过div A时,应该出现div B,然后如果鼠标超过A或B,则div B应保持打开状态。如果鼠标不在A和B之间,则B应该消失。 (正如您可能认为这是一个简单的工具提示脚本)

I have two div classes, say A and B. When the mouse is over div A, div B should appear, then if the mouse is over A or B, div B should stay opened. If the mouse is out of both, A and B divs, B should disappear. (As you probably guess this is a simple tooltip script)

这是我写的jquery代码:

This is the jquery code I wrote:

$(document).ready(function() {
    function show() {
        $("BBB").css({'display':'block'});
    }

    $("AAA").each(function() {
        $(this).mouseover(function() {
            show();
        });

        $(this).mouseleave(function() {
            time = setTimeout("hide()", 200);
        });

        $("BBB").mouseleave(function() {
            setTimeout("hide()", 200);
        });

        $("BBB").mouseenter(function() {
            clearTimeout(time);
        });
    });
});

function hide() {
    $("BBB").css({'display':'none'});
}

问题是当我从B移动到A时,B消失了!我希望它只有在鼠标既不是A,也不是B时才会消失。我该如何解决这个问题呢?

The problem is that when I move from B to A, B disappears! I want to it to disappear only if the mouse is neither over A, nor B. How can I fix this problem?

推荐答案

您的代码存在一些小问题。现在正在咬你的那个是当你输入AAA时你没有清除BBB的超时。您可以通过向AAA的鼠标悬停处理程序添加 clearTimeout 来解决此问题。

There are a few small problems with your code. The one which is biting your right now is that you aren't clearing BBB's timeout when you enter AAA. You can fix this by adding a clearTimeout to AAA's mouseover handler.

其次,在每次设置之前清除此类超时是最安全的,这样如果发生意外情况,您就不会覆盖超时跟踪。 (清除超时总是安全的,即使它已经无效或已经发生。)

Secondly, it's safest to clear this kind of timeout before you set it each time, so that you don't have your timeout tracking overwritten if something unexpected happens. (It's always safe to clear a timeout, even if it's invalid or has already occurred.)

最后,虽然这很可能只是示例代码中的一个问题,但是将时间泄漏到全局对象中。 ; - )

Lastly, though this is most likely only a problem in your example code, you're leaking time into the global object. ;-)

请改为尝试:

$(document).ready(function() {
    var time;

    function show() {
        $("BBB").css({'display':'block'});
    }

    $("AAA").each(function() {
        $(this).mouseover(function() {
            clearTimeout(time);
            show();
        });

        $(this).mouseleave(function() {
            clearTimeout(time);
            time = setTimeout("hide()", 200);
        });

        $("BBB").mouseleave(function() {
            clearTimeout(time);
            time = setTimeout("hide()", 200);
        });

        $("BBB").mouseenter(function() {
            clearTimeout(time);
        });
    });
});

function hide() {
    $("BBB").css({'display':'none'});
}

这篇关于如果鼠标超过div,则取消setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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