Hide menu items one-by-one on window resize

你说的曾经没有我的故事 提交于 2019-12-05 09:39:22
stylefish

I got it working only with CSS. The menu items will break to the next line, but the nav has a fixed size with overflow: hidden, so you'll not see them.

I made a Codepen with my solution. The main changes are: change the nav to fixed height:

.nav {
  height: 50px;
  width: 100%;
  overflow: hidden;
  width: 100%;
}

and move the search item in front of the menu

<div class="item-left">Logo</div>
<div class="item-right">Search & Dropdown</div>
<div class="menu">

and then I floated not the whole menu but every single item to left:

.menu a{
  float: left;
  height: 50px;
}

here's the link to the Codepen: http://codepen.io/anon/pen/bdzKYX

It's going to be hard to solve this in pure CSS, if you don't already know the widths of the menu items, and even then, you would have to keep updating the widths in the media queries.

Here's a rough solution in JavaScript - http://jsfiddle.net/vyder/eukr6m40/

$(document).ready(function() {
    var resizeMenu = function() {
        var windowWidth = $(this).width();

        // The width of stuff that needs to always be visible
        var fixedWidth = $('.item-left').width() + $('.item-right').width();

        // Remaining width that the menu can occupy
        var availableWidth = windowWidth - fixedWidth;

        resizeMenuToWidth(availableWidth);
    };

    var resizeMenuToWidth = function(availableWidth) {
        var widthSoFar = 0;

        // Iterate through menu items
        $('.menu a').each(function() {
            var itemWidth = $(this).width();

            // If the menu width has already exceeded the available space,
            // or if this menu item will cause it to exceed the space
            if( widthSoFar > availableWidth || (widthSoFar + itemWidth > availableWidth) ) {
                // Start hiding the menu items
                $(this).hide();
            } else {
                // Otherwise, show the menu item, and update the width count
                $(this).show();
                widthSoFar += itemWidth;
            }
        });
    };

    // Resize menu to when the page loads
    resizeMenu();

    // Also resize menu when the window is resized
    $(window).resize(resizeMenu);
});

It's a bit choppy on my browser, but you can probably build on this to make the resizing smoother.

Let me know if you have questions.

You need to use media queries for that, for example:

@media (max-width: 1200px) { 
    .item-right { 
        display: none; 
    } 
}

Reference

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