2

I have 2 drop-down menus for a mobile responsive site, one is for blog categories and another for a drop-down search box. These work fine but when you open one, then another it can look a little messy. I have been looking for something that when one is open and a user clicks to open another, listen out and close it. I have had a research and i have found that most functions use 'parent' and 'child' but not sure how it can apply to my snippet of code. I have also looked into removing classes but nothing seems to do the trick. If anyone has any suggestions to my problem i'd be grateful.

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 to toggle both drop-downs for mobile and small screens:

$('.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(); });
4

1 回答 1

3

之前$(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()

于 2013-04-18T10:24:07.000 回答