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

CSS : Collapsing navigation, one element at a time

本文关键字:一次 一个 元素 折叠 CSS 导航      更新时间:2023-09-26

折叠导航,就像你从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

我总是可以硬编码像素值,但如果我添加一个链接元素或更改其中的文本,那么我就不必考虑调整像素值,这将是一个很棒的解决方案。

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

我想你的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函数的详细信息,请参阅此处的文档。resize() | jQuery

我希望能帮助你,如果你有任何关于代码的问题,写一个评论^^

检查媒体查询它们可能有助于有这种行为媒体查询