当导航滚动到页面元素中某个元素时,导航显示。
HTML
<div class="header">我是顶部导航栏</div>
<div class="content">
<div class="sk">秒杀模块</div>
</div>
<div class="backtop">
<img src="./images/close2.png" alt="">
<a href="javascript:;"></a>
</div>
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.content {
overflow: hidden;
width: 1000px;
height: 3000px;
background-color: pink;
margin: 0 auto;
}
.backtop {
display: none;
width: 50px;
left: 50%;
margin: 0 0 0 505px;
position: fixed;
bottom: 60px;
z-index: 100;
}
.backtop a {
height: 50px;
width: 50px;
background: url(./images/bg2.png) 0 -600px no-repeat;
opacity: 0.35;
overflow: hidden;
display: block;
text-indent: -999em;
cursor: pointer;
}
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 80px;
background-color: purple;
text-align: center;
color: #fff;
line-height: 80px;
font-size: 30px;
transition: all .3s;
}
.sk {
width: 300px;
height: 300px;
background-color: skyblue;
margin-top: 500px;
}
JS
//获取头部
const header = document.querySelector('.header')
//获取指定位置
const sk = document.querySelector('.sk')
//给窗口绑定滚动事件
window.addEventListener('scroll',function(){
//获取当前窗口滚动的高度
let n = document.documentElement.scrollTop
//判断页面滚动的高度是否大于等于指定位置的高度,如果是就显示,不是就隐藏
header.style.top = n >= sk.offsetTop ? 0 : '-80px'
})