2011-07-27 21 views
0

我有2個div標籤,它們模擬了一個下拉菜單。當單擊外部div時,內部div將在其下面顯示一些鏈接。我只想在鼠標離開div時隱藏自己的內部div。模擬使用jQuery的簡單菜單的問題

下面是代碼是如何失敗的:

  1. 點擊外DIV。
  2. 不要輸入內部div。
  3. 向上,向左或向右移動鼠標離開外部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消失,當我試圖鼠標懸停這是由於部分LINE-HEIGHT問題我的代碼是有。經過仔細檢查(1600倍放大IE)我發現我的問題,我現在有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(); 
}); 

回答

1

我會嘗試: http://jsfiddle.net/shaneburgess/k5WRG/1/

// Toggle the menu. 
    $('.toggleMenu').click(function() 
    { 
     $(this).find('.menu').toggle(); 
    }); 

    // Hide the menu when the mouse leaves the tag. 
    $('.toggleMenu').mouseleave(function() 
    { 
     $(this).find(".menu").hide(); 
    }); 
+1

做好我的工作,並在獲得接受後一個小時提供我的答案;) – AlienWebguy

+0

@AlienWebguy被動攻擊很多?大聲笑 – Chev

+0

LOL是啊S.O.的政治。讓我有時哈哈 – AlienWebguy

0

由於.menu.toggleMenu孩子可以在mouseleave()事件簡單地分配給母公司,它都將影響。這是使用mouseleave()而不是mouseout()的主要好處。

$('.toggleMenu').mouseleave(function() 
{ 
    $(this).children('.menu').hide(); 
}); 

工作演示:http://jsfiddle.net/AlienWebguy/hNT6P/

0

這裏有您需要的代碼:



    $(".toggleMenu").live({ 
     click: function() { 
     $(this).find('.menu').show(); 
     }, 
     mouseleave: function() { 
     $(this).find('.menu').hide(); 
     } 
    }); 

因爲你正在使用的切換功能,它不會再次,除非你再次點擊隱藏。這是對的jsfiddle http://jsfiddle.net/Skooljester/9Dfjr/10/

更新:可以縮短$(this).find('.menu').show();$('.menu').show();,這無二.hide();線爲好。

+0

當我把鼠標移動到單擊內部DIV的鏈接,內格來隱藏自身,因此,菜單項是不可點擊。這是我描述的問題,如果我將外部div連接到一個mouseout事件,那麼內部div隱藏自己。 – Halcyon

+0

通過使用建議的AlienWebguy這樣的'mouseleave',您可以得到相同的結果。請參閱我評論中的修改代碼。 –