jQuery horizontal slide toggle navigation

2019-05-18 19:34发布

I'm looking to make a simple nested navigation menu that "slides" or "flys" out horizontally-left on hover. I assume the only way to achieve this is with jQuery so I have been playing around with it.

Initial State

enter image description here

Hover State

EDIT: I realize this picture looks a bit wrong. I want the entire ul.sub-menu (ie: PEOPLE & APPROACH) to slide out together, not sequentially.

enter image description here

The general structure is:

<nav>
<ul>
    <li>ABOUT
        <ul class="sub-menu">
            <li>PEOPLE</li>
            <li>APPROACH</li>
        </ul>
    </li>
    <li>PROJECTS</li>
    <li>CONTACT</li>
</ul>
</nav>

My jQuery is:

$("nav li").on('hover', function(){
    $(this).children(".sub-menu").animate({width: 'toggle'});
});

Currently my li's are floated.

My issue is when I hover over the parent LI, the .sub-menu fades in but is down a line and everything is jumping around due to floats.

Can someone point me in the right direction?

1条回答
beautiful°
2楼-- · 2019-05-18 19:46

Is this what you were going for? You were missing a display:inline-block property from your CSS I believe. By using an inline block, each element with that property will retain block features (width, height, etc) but also remain inline (no breaks before or after). Without the block part, it makes no sense to apply a width modification.

CSS:

<style type='text/css'>
    nav li {
        display: inline;
        list-style: none;
    }

    .sub-menu {
        display: inline-block;
        white-space: nowrap;
        padding: 0;
        margin: 0;
    }
</style>

Javascript:

<script>
    $(function() {
        $('.sub-menu').hide();

        $('.link').hover(
            function() {            
                $('.sub-menu', this).stop().animate({
                    width: 'toggle',
                    opacity: 'toggle'
                } /* [, duration in ms] */);
            }
        );
    });
</script>

HTML:

<nav>
    <ul>
        <li class="link">ABOUT
            <ul class="sub-menu">
                <li>PEOPLE</li>
                <li>APPROACH</li>
            </ul>
        </li>
        <li class="link">PROJECTS
            <ul class="sub-menu">
                <li>ONE</li>
                <li>TWO</li>
            </ul>
        </li>
        <li>CONTACT</li>
    </ul>
</nav>
查看更多
登录 后发表回答