固定導航欄案例 <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0 } img { vertical-align: top; ...
固定導航欄案例
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0 } img { vertical-align: top; } .main { margin: 10px auto 0; width: 1000px; } .fixed { position: fixed; top: 0; left: 0; } </style> <script src="../jquery-1.12.4.js"></script> <script> $(function () { $(window).scroll(function () { //判斷捲去的高度超過topPart的高度 if ($(window).scrollTop() >= $(".top").height()) { //1. 讓navBar有固定定位 $(".nav").addClass("fixed"); //2. 讓mainPart有一個marginTop $(".main").css("marginTop", $(".nav").height() + 10); } else { $(".nav").removeClass("fixed"); $(".main").css("marginTop", 10); } }); }); </script> </head> <body> <div class="top" id="topPart"> <img src="images/top.png" alt="" /> </div> <div class="nav" id="navBar"> <img src="images/nav.png" alt="" /> </div> <div class="main" id="mainPart"> <img src="images/main.png" alt="" /> </div> </body> </html>