我们在前端开发当中想要页面滚动到某个位置的时候显示和隐藏。在初步的学习者搞不懂怎么样实现这样的功能 ,这下来我们看看这么样实现导航栏的显示与隐藏功能
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: -80px;
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;
}
JavaScript部分(js)
// 1.获取元素
let sk = document.querySelector('.sk')
let header = document.querySelector('.header')
// 页面滚动事件
window.addEventListener('scroll' , function(){
// 获取滚动距离
// console.log(document.documentElement.scrollTop);
let top = document.documentElement.scrollTop
// 获取秒杀的位置
// console.log(sk.offsetTop);
let sktop = sk.offsetTop
// 判断什么时候显示和隐藏
if(top >= sktop){
header.style.top = '0'
}
else{
header.style.top = '-80px'
}
})
结果图
隐藏
显示