在 window 调整大小时逐一隐藏菜单项

Hide menu items one-by-one on window resize

我正在开发一个导航栏,该导航栏由向左浮动的徽标和菜单项以及向右浮动的搜索栏和下拉按钮组成。当浏览器 window 达到一定的小尺寸时,导航栏元素将开始跳到下一行,因为 space 已经不够了。

看这里:http://codepen.io/anon/pen/YXBaEK

如果水平 space 超出 运行,我希望每个菜单项都一个接一个地消失,而不是开始新的一行。 (我仍然在搜索栏旁边的下拉菜单中有菜单链接)。

HTML

<div class="nav">
  <div class="item-left">Logo</div>
  <div class="menu">
    <a>-------Menu Item 1-------</a>
    <a>-------Menu Item 2-------</a>
    <a>-------Menu Item 3-------</a>
    <a>-------Menu Item 4-------</a>
    <a>-------Menu Item 5-------</a>
  </div>
  <div class="item-right">Search & Dropdown</div>
</div>

CSS

.nav {
  width: 100%;
}

.item-left {
  width: 300px;
  height: 50px;
  background-color: green;
  float: left;
}

.item-right {
  width: 300px;
  height: 50px;
  background-color: red;
  float: right;
}

.menu {
  height: 50px;
  background-color: yellow;
  float: left;
}

感谢您的帮助

编辑:菜单项的数量和内容不是静态的。不知道会有多少,里面写的是什么

您需要为此使用媒体查询,例如:

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

Reference

如果您还不知道菜单项的宽度,那么纯 CSS 很难解决这个问题,即便如此,您也必须不断更新媒体中的宽度查询。

这里是 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);
});

它在我的浏览器上有点不稳定,但您可以在此基础上进行调整,使调整大小更顺畅。

如果您有任何问题,请告诉我。

我只在 CSS 上使用它。菜单项将换行到下一行,但导航栏的大小固定且溢出:隐藏,因此您将看不到它们。

我用我的解决方案做了一个 Codepen。 主要变化是:将导航更改为固定高度:

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

并将搜索项移到菜单前面

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

然后我不是将整个菜单而是向左浮动每个项目:

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

这是 Codepen 的 link: http://codepen.io/anon/pen/bdzKYX