CSS:折叠导航,一次一个元素

时间:2013-06-14 12:06:25

标签: javascript css

折叠导航,就像您从Twitter Bootstrap获得的那样,是一种“全有或全无”的方法,可以显示全部或隐藏所有导航元素。

但是,当空间变得越来越小时,有没有办法逐个隐藏导航元素?那就是:

640px:
Link 1 | Link 2 | Link 3 | Link 4 | Link 5

600px:
Link 1 | Link 2 | Link 3 | Link 4 | More

560px:
Link 1 | Link 2 | Link 3 | More

我总是可以对像素值进行硬编码,但是如果我不需要调整像素值,如果我添加一个链接元素或更改一个

2 个答案:

答案 0 :(得分:1)

检查可能有助于此行为的媒体查询media queries

答案 1 :(得分:1)

我写了一个例子来说明你要做什么:

我认为你有这样的HTML代码:

<html>
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.9.1.js"></script>

<script type="text/javascript" src="js/resize.js"></script>
</head>
<body>
<div id="navigation">
    <a href="#" id="link1">link1</a> <span id="2">|</span> <a href="#" id="link2">link2</a> <span id="3">|</span> <a href="#" id="link3">link3</a> <span id="4">|</span> <a href="#" id="link4">link4</a> <span id="5">|</span> <a href="#" id="link5">link5</a> 
</div>

</body>
</html>

如您所见,我添加了一个javascript代码<script type="text/javascript" src="js/resize.js"></script> in the head of the page,此文件如下所示:

// resize.js

$(document).ready(function(){
  // add a (more) link with javascript to ensure that it exist only if javascript is enabled
  $("#navigation").append('<a href="#" id="more">more</a>'); // #navigation is a div container of our links

  // in the load of document , you check the width of the browser and apply hide or show links switch what do you need
  var width_of_window = $(window).width();

  if (width_of_window <= 560) {
    $("#link5, #link4, #5, #4").hide(); 
  }

  if(width_of_window > 560 && width_of_window <= 600){
    $("#link4").show(); $("#link5").hide(); 
  }

  if(width_of_window >= 640){
    $("#more").hide();
  }


  // here resize function is handled when you resize the navigator 
  $(window).resize(function() {
    width_of_window = $(window).width(); // get the width of the window each time you resize it

  //apply what do you need

    if (width_of_window <= 560) {
        $("#link5, #link4, #5, #4").hide(); // #link5 and link4 are the id of links and #5, #4 are separator '|' between links (i added | separator between span, see html code)
        if( $("#more").is(':hidden') ){
            $("#more").show();
        }
     }

     if(width_of_window > 560 && width_of_window <= 600){

        $("#link4").show(); $("#link5").hide(); 
        if( $("#more").is(':hidden') ){
            $("#more").show();
        }
     }


     if(width_of_window >= 640){
        $("#more").hide();
        $("#link4, #link5").show();
     }
  });


});

有关调整大小功能的更多详细信息,请参阅此处的文档.resize() | jQuery

我希望可以帮助您,如果您对代码有任何疑问,请发表评论^^