javascript - 如果鼠标在 div 上,则取消 setTimeout

标签 javascript jquery

我有两个 div 类,比如 A 和 B。当鼠标悬停在 div A 上时,div B 应该出现,然后如果鼠标悬停在 A 或 B 上,div B 应该保持打开状态。如果鼠标不在 A 和 B div 中,B 应该消失。 (您可能猜到这是一个简单的工具提示脚本)

enter image description here

这是我写的 jquery 代码:

$(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 上时消失。我该如何解决这个问题?

最佳答案

首先,将B放在A中:

<div class="a">
    AAA
    <div class="b">
        BBB
    </div>
</div>

然后,放弃你的 javascript,使用普通的旧 css 让生活更轻松:

.b
{
    display: none;
}
.a:hover .b
{
    display: block;
}

编辑 - 这是一个使用 CSS 技术的实例:http://jsfiddle.net/gilly3/sBwTa/1/

编辑 - 如果您必须使用 JavaScript,只需将 clearTimeout(time) 添加到 show()。但是,让我们也简化您的代码:

$(function()
{
    var time = 0;
    function show()
    {
        clearTimeout(time);
        $("BBB").show(); // Existing jQuery that does $().css("display","block")
    }
    function hide()
    {
        time = setTimeout(function()
        {
            $("BBB").hide();
        }, 200);
    }
    $("AAA,BBB").mouseenter(show).mouseleave(hide);
});

关于javascript - 如果鼠标在 div 上,则取消 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4949714/

相关文章:

javascript - 如何写日期 | ng 类中的日期 :"MM"?

javascript - 读取数据产生 null

javascript - 动态 ajax bootstrap 模态框无法正常工作

php - 如何为每个链接动态构建查询字符串?

javascript - Jquery Ajax表单没有成功消息

javascript - 无法将数据传递给函数 (jQuery)

javascript - CSS,HTML,使 div 文本保留在其 div 的中间,无论文本如何

javascript - jQuery 动画函数到纯 JavaScript

javascript - 单击即可扩展 DIV - 按需

javascript - 如何在 var 声明中获取该数组的第一个元素?