DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

基于Bootstrap 3的页眉页脚控制


对网页上页眉(header)、页脚(footer)的位置要求是:

  1. 当网页正文内容短于一页时,不论浏览器窗口尺寸如何,页眉要在顶端,页脚在底端,不能出现页脚下面还有空白的情况;

  2. 当网页正文内容长于一页时,不论浏览器窗口尺寸如何,页眉页脚不能遮挡住正文内容,当使用滚轮上下滚动时,页眉页脚要随之滚动;

也就是sticky header/footer效果。下面是符合此要求的一个精简Meteor实现:

$ meteor create stickyHeaderFooter
$ cd stickyHeaderFooter
$ ln -s ../client
$ tree client
client
├── css
│   └── bootstrap.min.css
└── lib
    └── bootstrap.min.js
$ cat << EOF > stickyHeaderFooter.html
<head>
  <title>Sticky Header & Footer</title>
</head>

<body>
  <nav class="navbar navbar-default navbar-static-top">
    <div class="container">Here is Header</div>
  </nav>
  <h1>Sticky Header & Footer</h1>

  <div id="content" class="container">
    {{> hello}}
  </div>

  <div id="footer">
    <div class="navbar navbar-fixed-bottom">
      <div class="container">Here is the Footer</div>
    </div>
  </div>
</body>

<template name="hello">
  <button id="addline">Add a line</button>
  <button id="rmline">Remove a line</button>
  <div>
    {{#each samples}}
      <li>Item No: {{this}}</li>
    {{/each}}
  </div>
</template>
EOF

$ cat << EOF > stickyHeaderFooter.css
html {
  position: relative;
  min-height: 100%;
}

#content { padding-bottom: 70px; }

#footer .navbar {
  position: absolute;
}
EOF

$ cat << EOF > stickyHeaderFooter.js
if (Meteor.isClient) {
  Session.setDefault("sample", [1,2,3]);

  Template.hello.helpers({
    samples: function () {
      return Session.get("sample");
    }
  });

  Template.hello.events({
    'click #addline': function () {
      var sl = Session.get("sample");
      sl.push(sl[sl.length - 1] + 1);
      Session.set("sample", sl);
    },
    'click #rmline': function () {
      var sl = Session.get("sample");
      if (sl.length > 1) {
        sl.pop();
      }
      Session.set("sample", sl);
    }
  });
}
$ meteor

Meteor服务启动完毕后,运行firefox localhost:3000,通过点击"Add a line"增加正文长度,点击"Remove a line"减小正文长度,同时改变浏览器窗口大小,验证代码是否符合上面的要求。

这里面页眉的设置相对简单,用Bootstrap 3的navbar-static-top就能够达到要求。

页脚基于Bootstrap 3的"navbar navbar-fixed-bottom"实现,但这个类本身的功能是把页脚固定在浏览器底部,而不论正文内容长短, 所以要通过在css文件中设置格式的方法实现sticky footer效果, 在css文件的3段设置中,前两段负责避免正文与页脚重叠,第3段的作用是保证页脚始终在正文之后,而不是固定在浏览器窗口底端。

Html文件中的container属性是bootstrap 3网格系统的容器,用来对齐各个行元素中的各列,并自动控制行、列元素的页边距, 这里使用container是为了避免在css中手工设定padding值。

本文的实现方法借鉴了Flushing footer to bottom of the page, twitter bootstrap中Régis B.的回答, 但对其答案进行了精简。

container部分基于When should I use class container and row?。

说明:实例代码用软链接引入Bootstrap文件,是为了节约空间,也可以直接把client文件夹拷贝到当前目录中。



Published

Jan 18, 2015

Last Updated

Jan 18, 2015

Category

Tech

Tags

  • bootstrap 4
  • footer 1
  • header 1
  • html 9
  • web 16

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor