0

我有一个菜单,我试图让子菜单在鼠标悬停时淡入,并在鼠标离开时淡出。我尝试了几种解决方案,其中大多数导致菜单在悬停时立即消失,而不是在 mouseleave/mouseout 时。下面的代码是我认为最有意义的代码。但结果是菜单淡入,但不淡出。

<script type="text/javascript">
$(document).ready(function(){

      //When hovering a top-level link, submenu fadein. 
      $('.toppunkt a').mouseenter(function(){
      $('ul.sub-menu').fadeIn();
      });

      //When leaving the submenu, fadeout.  
      $('.ul.sub-menu').mouseleave(function(){
      $('ul.sub-menu').fadeOut();
      });
});
</script>
4

2 回答 2

2

这可能会或可能不会帮助您,但您似乎在 mouseleave 上检查了错误的项目......

http://jsfiddle.net/Mutmatt/3ppr8/14/

更好的是,您可能希望这个菜单系统的行为方式就像这个 jsfiddle:

http://jsfiddle.net/Mutmatt/3ppr8/23/

看看那个。不要忘记标记正确答案以供将来参考

代码:JS:

jQuery(document).ready(function() {
    jQuery('#topmenu li').hover(
        //When hovering a top-level link, submenu fadein. 
        function() {
            jQuery('ul', this).stop().fadeIn();
        },
        //When leaving the submenu, fadeout.  
        function() {
            jQuery('ul', this).stop().fadeOut();
        }
    );
});​

HTML:

<ul id="topmenu">
    <li><a href="yep">yep</a>
        <ul class="sub-menu" style="display: none;">
            <li><a href="derp">derp</a></li>
            <li><a href="yerp">yerp</a></li>
        </ul>
    </li>
</ul>​
于 2012-09-24T18:35:44.480 回答
1

Could be the extra '.' in getting the sub-menu in the mouse leave function. I wrote up a solution using divs.

Here is the fiddle: http://jsfiddle.net/PAWQr/12/

Hopefully this helps.

HTML:

<div  class="toppunkt">
    <a href="" action="">Here is a list</a>
    <div class="sub-menu" style="width:70px; border: 1px dotted gray; display: none;">    
        <ul>
            <li>Option1</i>
            <li>Option2</i>
        </ul>
    </div>       
</div>

Script:

$(document).ready(function(){

  //When hovering a top-level link, submenu fadein. 
  $('.toppunkt a').mouseenter(function(){
      //alert('mouse enter');
      $('.sub-menu').fadeIn();
  });

  //When leaving the submenu, fadeout.  
  $('.sub-menu').mouseleave(function(){
      $('.sub-menu').fadeOut();
  });
​});
于 2012-09-24T18:58:05.293 回答