代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*
{
margin:0;
padding: 0;
}
body
{
height: 2000px;
/* 保证滚动条的出现 */
}
.nav
{
background-color: darkcyan;
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: darkgray;
}
.fixed a
{
color:brown;
}
</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>
</html>
效果展示