朋友問.如何在頁面向下移時.
原本在中間位置的導航欄會在相應的時間鎖定在頂部.
沒用 jQuery.純 JS 實現不知道支持度如何.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>This is a test page</title> <style type="text/css"> body { margin: 0px; font-size: 12px; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } a { text-decoration: none; color: #FFF; } #menu { position: absolute; top: 100px; background: #F00; width: 100%; padding: 5px; z-index: 1 } #menu a { display: inline-block; width: 33%; text-align: center; } #container { position: relative; margin-top: 150px; text-align: center; } </style> <script type="text/javascript"> (function(window) { var scrollMenu = function() { var menu = document.getElementById("menu"), menuOriginalOffsetTop = menu.offsetTop, menuOnTop = false, scrollTop = function() { return document.documentElement.scrollTop || document.body.scrollTop; }; window.onscroll = function() { if (menuOnTop === false && menu.offsetTop - scrollTop() < 0) { menuOnTop = true; menu.style.top = 0; menu.style.position = 'fixed'; } if (scrollTop() <= menuOriginalOffsetTop) { menuOnTop = false; menu.style.top = menuOriginalOffsetTop + 'px'; menu.style.position = 'absolute'; } } } if (typeof window.addEventListener != "undefined") { window.addEventListener("load", scrollMenu, false); }else{ window.attachEvent("onload", scrollMenu) } })(window); </script> </head> <body> <div id="wrapper"> <div id="navigation"> <nav id="menu"> <a href="#about">About</a> <a href="#exp">Experience</a> <a href="#con">Contact</a> </nav> </div> <div id="container"> <section class="space-holder"> <img src="http://placehold.it/950x550/09f/fff"> </section> <section class="space-holder"> <img src="http://placehold.it/950x550/0f9/fff"> </section> <section class="space-holder"> <img src="http://placehold.it/950x550/f09/fff"> </section> </div> </div> </body> </html>
|