欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

固定导航栏

程序员文章站 2022-03-13 13:56:40
...
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>固定导航栏</title>
  8. <style>
  9. *{
  10. margin:0;
  11. padding:0;
  12. }
  13. #one{
  14. background:goldenrod;
  15. height:100px;
  16. width:500px;
  17. font-size:20px;
  18. }
  19. #two{
  20. background:rgb(109, 240, 245);
  21. height:500px;
  22. width:500px;
  23. font-size:20px;
  24. }
  25. #three{
  26. background:rgb(247, 157, 194);
  27. height:500px;
  28. width:500px;
  29. font-size:20px;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <div id="one">这是顶部</div>
  35. <div id="two">这是中间</div>
  36. <div id="three">这是尾部</div>
  37. <script>
  38. window.onload = function() {
  39. var one = document.getElementById('one');
  40. var two = document.getElementById('two');
  41. var three = document.getElementById('three');
  42. window.onscroll=function(){
  43. if(document.documentElement.scrollTop >= one.offsetHeight ){
  44. one.style.cssText="position:fixed;top:0px;";
  45. two.style.marginTop = one.offsetHeight+"px";
  46. }else {
  47. one.style.cssText="position:static;";
  48. two.style.marginTop ='0px';
  49. }
  50. }
  51. }
  52. </script>
  53. </body>
  54. </html>

固定导航栏

固定导航栏