~~~
<style>
*{
margin:0;
padding: 0;
}
body{
height: 2000px;
}
.nav{
background: pink;
padding:0 10%;
transition: all 1s;
}
.nav ul{
list-style: none;
overflow: hidden;
}
.nav li{
float: left;
margin-right: 30px;
}
.nav a{
line-height: 100px;
}
.fixed{
position: fixed;
width: 100%;
background: plum;
}
.fixed a{
color: #fff !important;
}
</style>
~~~
~~~
<body>
<div class="nav" id="nav">
<ul>
<li><a>HOME</a></li>
<li><a>ABOUT</a></li>
<li><a>HOBBY</a></li>
<li><a>CONTACT</a></li>
</ul>
</div>
<script>
window.onload=function(){
var nav=document.getElementById("nav");
document.onscroll=function(){
var sTop=document.documentElement.scrollTop;
console.log(sTop);
if(sTop>0){
nav.className="nav fixed";
}
else{
nav.className="nav";
}
}
}
</script>
</body>
~~~
效果图如下:
![](https://box.kancloud.cn/7ec8c3e059e06f7d06e801847d34e64f_1349x369.gif)