如何处理导航项目的溢出?

时间:2015-05-29 14:08:19

标签: javascript

假设我正在创建一个网页,并拥有一堆导航项,如下所示:

Home About Contact Help Something Something-Else Another

根据浏览器宽度,我希望有任何不适合放入下拉列表的项目,如下所示:

闭:

Home About Contact Help ... 

打开

Home About Contact Help ... 
                 --------^-------------
                 |     Something      | 
                 |   Something-Else   |
                 |      Another       |
                 ----------------------

有没有简单的方法呢?

1 个答案:

答案 0 :(得分:1)

你可以用JS做到这一切:

window.onresize = function(event) {
  //Get the window width
  var winWidth = window.width;
  var navItemsWidth = 0; //you'll use this in a minute...
  var extraNavItems = []; //you'll use this in a minute...

  //Then iterate through each nav
  var navItems = document.getElementsByClassName('navItem');
  for (var i = 0; i < navItems.length; i++) {
    //Check the width of each item and compare to win width
    navItemsWidth += navItems[i].innerWidth;
    //if the width is greater than screen width...
    if(navItemsWidth > winWidth) {
       //add Items to an array
       extraNavItems.push(navItems[i]);
       //or you could add them to your drop down here...
    } else {
       //if you are still under winWidth add them to your navBar
       document.getElementById('navBar').html += navItems[i];
    }
  }
};

或者您也可以查看CSS媒体查询:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries