【问题标题】:Hide menu onClick隐藏菜单 onClick
【发布时间】:2012-06-09 17:25:00
【问题描述】:

我有这个下拉菜单,只要我的用户点击链接,它就会向下滑动。但是,每当用户单击页面上的某个位置(当然不在菜单上)时,我不知道如何使它滑动。

我的 CSS 如下所示:

<li class="da-header-button message">
    <span class="da-button-count">32</span>
    <a href="#">Notifications</a>
    <ul class="subnav">
        <li class="head"><span class="bold">Notificatons</span></li>
        <li class="item"><a href="#">Under menu</a></li>
        <li class="item"><a href="#">Under menu</a></li>
    </ul>
</li>

我当前的 jQuery 代码如下所示:

jQuery("ul.topnav li").click(function() { //When trigger is clicked...  
    //Following events are applied to the subnav itself (moving subnav up and down)  
    jQuery(this).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  
    jQuery(this).hover(function() {  
    }, function(){  
        jQuery(this).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
    });  
});

如果我将最后一个 jQuery 函数从这个:jQuery(this).hover(function() 编辑到这个:jQuery(this).click(function() 它不起作用,因为它只会向下滑动,然后立即向上。

感谢您的帮助。

编辑:

谢谢各位!但是,如果我同时打开其中两个子菜单怎么办?我怎样才能防止这种情况发生?

我只想允许打开 1 个。

【问题讨论】:

    标签: jquery html css drop-down-menu menu


    【解决方案1】:

    当点击传播到文档时,向上滑动所有可见菜单:

    $(document).on("click", function(){
        $(".subnav:visible").slideUp();
    });
    

    然后通过停止事件传播来防止在菜单中发生这种情况。

    $("ul.topnav").on("click", "li", function(e){
        e.stopPropagation();
        $(".subnav:visible", $(this).siblings()).slideUp("fast");
        $(".subnav", this).slideDown();
    });
    

    小提琴:http://jsfiddle.net/jonathansampson/qQsdN/

    【讨论】:

    • 谢谢!这很好用。因为我遇到了一个新问题,所以我用一个新问题更新了我的答案。
    • 在您的点击处理程序中,就在您显示子菜单之前,向上滑动所有可见的子菜单。
    【解决方案2】:

    这个 JQuery 应该可以工作:

    $('#nav li').hover(
        function () {
            //show its submenu
            $('ul', this).slideDown(100);
    
        },
        function () {
            //hide its submenu
            $('ul', this).slideUp(100);        
        }
    );
    

    【讨论】:

      【解决方案3】:

      jQuery(this).find() 将找到“this”的后代。在您的代码中,由于新的闭包“function()”,“this”发生了变化。

      试试这个:

      jQuery("ul.topnav li").click(function() { //When trigger is clicked...  
      
          var me = this;
          //Following events are applied to the subnav itself (moving subnav up and down)  
          jQuery(me).find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click  
      
          jQuery(me).click(function() {  
          }, function(){  
              jQuery(me).find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up  
          });  
      
      });
      

      【讨论】:

        猜你喜欢
        • 2016-06-05
        • 2017-02-26
        • 1970-01-01
        • 1970-01-01
        • 2016-08-06
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多