~~~
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
}
.nav {
background-color: aqua;
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: cadetblue;
}
.fixed a {
color: #fff !important;
}
</style>
</head>
<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;
if(sTop>0){
nav.className = "nav fixed";
}else {
nav.className = "nav";
}
}
}
</script>
</body>
~~~
![](https://box.kancloud.cn/7fe09f2d64e0e88587ee405043ccc3f2_505x379.gif)