jQuery dropdown menu should expand if parent is active

心不动则不痛 提交于 2019-12-12 23:31:58

问题


I'm making a simple dropdown menu in jQuery. And it works fine. I'm having a problem though.

The problem is, that i need to keep the active page dropdown expanded In the example below the sub-menu that has the .inpath parent needs to always stay expanded. If you hover on another menu-item it should show the relevant subpages and when you hover out return to show the active subpages. Any help is greatly appriciated :-)!

My html:

<div id="menu">

            <ul>

                <li><a href="">Hvem</a></li>
                <li><a href="">Hvad</a>
                    <ul>
                    <li><a href="">Produkter</a></li>
                    <li><a href="">Leveringer</a></li>
                    </ul>
                </li>

                <li class="inpath"><a href="">Hvordan</a>

                    <ul>

                        <li><a href="">Reklame</a></li>
                        <li><a href="">PR</a></li>
                        <li><a href="">Websites</a></li>
                        <li><a href="">Illustrationer</a></li>

                    </ul>

                </li>
                <li class="last-item"><a href="">Sådan!</a></li>

            </ul>

            <div class="clear"><!--clearfix--></div>

        </div>

My jQuery:

 <script type="text/javascript">
        //mouseenter, mouseover, hover
        // mouseleave, mouseout,
    $(document).ready(function () { 
        $('#menu ul li ul').hide();
        $('#menu li').hover(
            function () {
                //show its submenu
                $('ul', this).slideDown(100);

            }, 
            function () {
                //hide its submenu
                $('ul', this).slideUp(100);         
            }
        );

    });

        </script>

回答1:


try removing .inpath from the original hide() and the hover(). You also need more specific selects using the > (direct descendant selector).

$(document).ready(function() {
    $('#menu > ul > li:not(.inpath) ul').hide();
    $('#menu > ul > li:not(.inpath)').hover(

    function() {
        $('ul', this).slideDown(100);
        $('#menu li.inpath ul').hide();
    }, function() {
        $('ul', this).slideUp(100);
        $('#menu li.inpath ul').show();
    });
});

http://jsfiddle.net/MGkQC/7/



来源:https://stackoverflow.com/questions/5181244/jquery-dropdown-menu-should-expand-if-parent-is-active

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!