<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>原生JS实现网页导航条特效</title>
<style>
*{
margin:0;
padding:0;
box-sizing:border-box;
word-wrap:break-word;
font-family:'微软雅黑',sans-serif;
}
body{
background:#000;
min-height:200vh;
}
header{
position:fixed;
top:0;
left:0;
width:100%;
display:flex;
align-items:center;
justify-content:space-between;
transition:0.6s;
padding:40px100px;
z-index:2;
}
header.sticky{
padding:5px100px;
background:#fff;
}
header.logo{
position:relative;
font-weight:700;
color:#fff;
text-decoration:none;
font-size:2em;
text-transform:uppercase;
letter-spacing:2px;
transition:0;
}
headerul{
position:relative;
display:flex;
justify-content:center;
align-items:center;
}
headerulli{
position:relative;
list-style:none;
}
headerullia{
position:relative;
margin:015px;
text-decoration:none;
color:#fff;
letter-spacing:2px;
font-weight:500px;
transition:0.5s;
}
.banner{
position:relative;
width:100%;
height:100vh;
background:url(bg.jpg);
background-size:cover;
}
header.sticky.logo,
header.stickyullia{
color:#000;
}
</style>
</head>
<body>
<header>
<ahref="#"class="logo">Logo</a>
<ul>
<li><ahref="#">首页</a></li>
<li><ahref="#">关于</a></li>
<li><ahref="#">服务</a></li>
<li><ahref="#">作品</a></li>
<li><ahref="#">联系</a></li>
</ul>
</header>
<sectionclass="banner"></section>
<script>
window.addEventListener('scroll',()=>{
letheader=document.querySelector('header')
//重要属性
header.classList.toggle('sticky',window.scrollY>0)
})
</script>
</body>
</html>
|