💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## JS实现滑动导航条固定 >效果如图 ![](https://box.kancloud.cn/81b805312c8fd68a690f657473444bde_1638x115.gif) >html代码 ``` <div class="container" id="header"> <div class="nav"> <img src="images/adm.jpg" alt=""> <h1>MrXuxuの前端之行</h1> <ul> <li id="home"><a>HOME</a></li> <li id="about"><a>ABOUT</a></li> <li id="hobby"><a>HOBBY</a></li> <li id="skill"><a>SKILL</a></li> <li id="work"><a>WORK</a></li> <li id="contact"><a>CONTACT</a></li> </ul> </div> </div> ``` >css代码 ``` * { margin: 0; padding: 0; } body { height: 2000px; background-color: rgb(66, 156, 230); } a { text-decoration: none; cursor: pointer; } .container { width: 100%; height: 70px; transition: all 1s; //动画切换效果时间为1s } .nav { width: 80%; margin: 0 auto; color: #fff; } .nav ul { float: right; } .nav li { float: left; list-style: none; line-height: 70px; margin-left: 20px; font-size: 15px; } .nav img { float: left; width: 50px; margin-top: 10px; border-radius: 50%; } .nav h1 { display: inline-block; height: 50px; line-height: 30px; margin-left: 40px; margin-top: 10px; padding: 5px 14px; border: 5px solid #fff; box-sizing: border-box; border-radius: 25px; } /* ------fixed------ */ .fixed { position: fixed; width: 100%; background-color: #fff; } .fixed a { color: black; } .fixed h1 { color: black; border: 5px solid black; } ``` >js代码 ``` window.onload = function(){ var header = document.getElementById("header"); var top = header.offsetTop;//获取导航条到顶部的高度 document.onscroll = function(){ var sTop = document.documentElement.scrollTop;//获取滚动距离 if(sTop>top){ header.className = "container fixed"; }else{ header.className = "container"; } } } ```