【发布时间】:2011-07-27 17:11:52
【问题描述】:
我有 2 个模拟下拉菜单的 div 标签。单击外部 div 时,内部 div 会在其下方显示一些链接。我希望内部 div 仅在鼠标离开任一 div 时才隐藏。
以下是代码失败的原因:
- 单击外部 div。
- 不要进入内部 div。
- 向上、向左或向右移动鼠标以离开外部 div。内部 div 应该隐藏自己,但不会。
我知道我需要一个 mouseout 事件挂钩到外部 div,但是当我这样做时,它会在我尝试进入内部 div 时隐藏它。
当鼠标离开任一 div 时,如何让内部 div 隐藏?
<style type="text/css">
div.toggleMenu { position: relative; }
div.menu { position: absolute; left: -3px; top: 19px; display: none; }
</style>
<div class="toggleMenu">
Toggle Menu
<div class="menu">
<ul>
<a href="http://www.google.com/"><li>Google</li></a>
<a href="http://www.yahoo.com/"><li>Yahoo</li></a>
<a href="http://www.bing.com/"><li>Bing</li></a>
</ul>
</div>
</div>
<script type="text/javascript">
// Toggle the menu.
$('.toggleMenu').click(function ()
{
$(this).find('.menu').toggle();
});
// Hide the menu when the mouse leaves the tag.
$('.menu').mouseleave(function ()
{
$(this).hide();
});
</script>
更新:当我尝试将鼠标悬停时,内部 div 消失的部分问题是由于我的代码遇到的行高问题。经过仔细检查(在 IE 中放大 1600 倍),我发现了我的问题,现在我让 jquery 以编程方式设置了高度。有兴趣的朋友可以看看最终代码:
$('.toggleMenu').click(function ()
{
if ($(this).find('.menu').css('display') == 'none')
{
// The menu needs to be positioned programmatically for the
// height due to the differences among browser interpretations of height.
var height = $('.toggleMenu').height() - 1;
$(this).find('.menu').css('top', height + 'px');
$(this).find('.menu').css('left', '-3px');
$(this).find('.menu').show();
}
else
{
$(this).find('.menu').hide();
}
});
// Hide the menu when the mouse leaves the tag.
$('.toggleMenu').mouseleave(function ()
{
$(this).find('.menu').hide();
});
【问题讨论】:
标签: jquery mouseevent