如何創建:粘性/固定導航欄
學習如何使用 CSS 和 JavaScript 創建一個“粘性”導航欄。
如何創建粘性導航欄
第一步 - 添加 HTML:
創建導航欄:
<div id="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div>
第二步 - 添加 CSS:
設置導航欄樣式:
/* 設置導航欄樣式 */ #navbar { overflow: hidden; background-color: #333; } /* 導航欄鏈接 */ #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px; text-decoration: none; } /* 頁面內容 */ .content { padding: 16px; } /* 當到達其滾動位置時,通過 JS 將 sticky 類添加到導航欄中 */ .sticky { position: fixed; top: 0; width: 100%; } /* 為頁面內容添加一些上內邊距,以防止突然的快速移動(因為導航欄在頁面頂部獲得新位置(position:fixed 和 top:0)) */ .sticky + .content { padding-top: 60px; }
第三步 - 添加 JavaScript:
// 當用戶滾動頁面時,執行myFunction window.onscroll = function() {myFunction()}; // 獲取導航欄 var navbar = document.getElementById("navbar"); // 獲取導航欄的偏移位置 var sticky = navbar.offsetTop; // 當您到達導航欄的滾動位置時,為其添加 sticky 類。當您離開滾動位置時,移除 "sticky" 類。 function myFunction() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") } else { navbar.classList.remove("sticky"); } }