对于移动响应网站,我有2个下拉菜单,一个是博客类别的菜单,另一个是下拉搜索框的菜单。这些可以正常工作,但是当您打开一个,然后打开另一个时,可能看起来有点混乱。我一直在寻找一种东西,当一个人打开时,用户单击以打开另一个人,然后听着然后关闭它。我进行了研究,发现大多数函数使用“父级”和“子级”,但不确定如何将其应用于我的代码段。我也研究过删除类,但似乎无济于事。如果有人对我的问题有任何建议,我将不胜感激。

的HTML

<div id="nav-mobile-responsive"><!--Mobile Navigation-->
        <div class="categories-mobile-responsive">
            <ul id="nav-1">
                <li>
                  <h3></h3>
                    <ul>
                        <?php wp_list_categories('&title_li=') ?>
                    </ul>
                </li>
           </ul>
        </div>
        <div class="searchbar-mobile-responsive">
            <ul id="nav-2">
                <li><h3></h3>
                    <ul>
                        <form method="get" id="searchform-mobile" action="<?php echo home_url( '/' ); ?>">
                        <div id="search-inputs">
                        <input type="text" value="" name="s" id="search-box" placeholder="SEARCH" />
                        <input type="hidden" name="ref_url" value="<?php esc_url($_SERVER['REQUEST_URI'])?>">
                        </div>
                        </form>
                    </ul>
                </li>
           </ul>
        </div>
    </div>


使用Javascript切换移动和小屏幕的下拉菜单:

$('.categories-mobile-responsive,.searchbar-mobile-responsive').click(function(){
                $(this).find('ul#nav-1,ul#nav-2').find('ul').slideToggle();
            });

$("#searchform-mobile").click(function(event){ event.stopPropagation(); });

最佳答案

$(this).find('ul#nav-1,ul#nav-2').find('ul').slideToggle();之前,只需滑动所有其他下拉菜单即可。

$('.categories-mobile-responsive,.searchbar-mobile-responsive').click(function(){
    $(this).siblings().find('ul ul').slideUp();
    $(this).find('ul#nav-1,ul#nav-2').find('ul').slideToggle();
});


额外:一些代码是不必要的,可以进行优化(除非您没有提供完整的HTML结构-在这种情况下,这可能会破坏它):

$('nav-mobile-responsive div').click(function(){ //only one selector
    $(this).siblings().find('ul ul').slideUp();
    $(this).find('ul ul').slideToggle(); //only call .find() once
});


来源

jQuery API - .slideUp()
jQuery API - .siblings()

07-24 09:49
查看更多