adding more button for list in responsive navigation

前端 未结 4 1091
北恋
北恋 2021-01-03 13:52

I have a navigation of lets say 12 items, and when resolution gets smaller items drop in a new line. I need to make that when an item doesn\'t fit on a navigation anymore it

4条回答
  •  心在旅途
    2021-01-03 14:08

    This question is too old, but i want to post my answer too. Maybe this is more cleaner and easier way. I have created a pen: https://codepen.io/sergi95/pen/bmNoML

    const $mainMenu = $("#mainMenu");
        const $autoNav = $("#autoNav");
        const $autoNavMore = $("#autoNavMore");
        const $autoNavMoreList = $("#autoNavMoreList");
        autoNavMore = () => {
            let childNumber = 2;
    
            if($(window).width() >= 320) {
                // GET MENU AND NAV WIDTH
                const $menuWidth = $mainMenu.width();
                const $autoNavWidth = $autoNav.width();
                if($autoNavWidth > $menuWidth) {
                    // CODE FIRES WHEN WINDOW SIZE GOES DOWN
                    $autoNav.children(`li:nth-last-child(${childNumber})`).prependTo($autoNavMoreList);
                    autoNavMore();
                } else {
                    // CODE FIRES WHEN WINDOW SIZE GOES UP
                    const $autoNavMoreFirst = $autoNavMoreList.children('li:first-child').width();
                    // CHECK IF ITEM HAS ENOUGH SPACE TO PLACE IN MENU
                    if(($autoNavWidth + $autoNavMoreFirst) < $menuWidth) {
                        $autoNavMoreList.children('li:first-child').insertBefore($autoNavMore);
                    }
                }
                if($autoNavMoreList.children().length > 0) {
                    $autoNavMore.show();
                    childNumber = 2;
                } else {
                    $autoNavMore.hide();
                    childNumber = 1;
                }
            }
        }
        // INIT 
        autoNavMore();
        $(window).resize(autoNavMore);
    
    
    .main-menu {
            max-width: 800px;
        }
        .main-nav {
            display: inline-flex;
            padding: 0;
            list-style: none;
        }
        .main-nav li a {
            padding: 10px;
            text-transform: capitalize;
            white-space: nowrap;
            font-size: 30px;
            font-family: sans-serif;
            text-decoration: none;
        }
        .more-btn {
            color: red;
        }
        .auto-nav-more {
            position: relative;
        }
        .auto-nav-more-list {
            position: absolute;
            right: 0;
            opacity: 0;
            visibility: hidden;
            transition: 0.2s;
            text-align: right;
            padding: 0;
            list-style: none;
            background: grey;
            border-radius: 4px;
        }
        .auto-nav-more:hover .auto-nav-more-list {
            opacity: 1;
            visibility: visible;
        }
    

提交回复
热议问题