DIV CSS 佈局教程網

菜單滾動到頂部後固定:JS 滾動事件實作
編輯:關於JavaScript     

效果

當頁面捲動到選單位置後,選單會固定在頂部,方便使用者隨時導航。

HTML

<div id="nav_keleyi_com">
  <a href="#">.NET</a>
  <a href="#">Javascript</a>
</div>

JS

function menuFixed(id) {
  var obj = document.getElementById(id);
  var top = obj.offsetTop;
  window.onscroll = function() {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    obj.style.position = scrollTop < top ? "relative" : "fixed";
  };
}
window.onload = function() {
  menuFixed("nav_keleyi_com");
};

注意

使用 position: fixed 後,原本佔用的文件流空間可能消失,必要時可加上佔位元素避免內容跳動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved