可以應用於移動端的頂部導航固定效果

admin發表於2017-02-23
本章節分享一段關於導航欄的程式碼例項。

它實現了導航欄固定於網頁的頂端,並且也實現了頁面的尺寸自適應效果。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
  list-style: none;
}
.wrapper {
  margin: 0 auto;
  background: #ccc;
}
.clear {
  clear: both;
  width: 100%;
  height: 0;
}
.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: "";
  height: 0;
  clear: both;
}
.center {
  overflow-x: hidden;
  overflow-y: auto;
}
.center p {
  font-size: 30px;
  line-height: 100px;
  height: 100px;
}
.header {
  height: 60px;
  background: red;
}
.header ul li {
  width: 25%;
  text-align: center;
  line-height: 60px;
  float: left;
  font-size: 20px;
}
.footer {
  height: 60px;
  background: blue;
}
.footer ul li {
  width: 25%;
  text-align: center;
  line-height: 60px;
  float: left;
  font-size: 20px;
  color: #fff;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(function () {
  autoSizeHeight();
  //拖動瀏覽器視窗導航也適應
  window.onresize = function () {  
    autoSizeHeight();
  }
})
 
//固定導航
function autoSizeHeight() {
  var footerH = 0;
  var winH = $(window).height();
  footerH = $(".footer").outerHeight(true);
  //滾動區域
  if ($(".center").length != 0) {
    var headerH = $(".center").position().top;
    $(".center").height(winH - footerH - headerH);
  }
}
</script>
</head>
<body>
  <div class="wrapper">
    <div class="header">
      <ul class="clearfix">
        <li>分類1</li>
        <li>分類2</li>
        <li>分類3</li>
        <li>分類4</li>
      </ul>
    </div>
    <div class="center" style="height:1000px;">
      <p>此處是內容區域</p>
      <p>此處是內容區域</p>
      <p>此處是內容區域</p>
      <p>此處是內容區域</p>
      <p>此處是內容區域</p>
    </div>
    <div class="footer">
      <ul class="clearfix">
        <li>分類1</li>
        <li>分類2</li>
        <li>分類3</li>
        <li>分類4</li>
      </ul>
    </div>
  </div>
</body>
</html>

相關文章