注意:
- 往下滑动到距离顶部一定距离,顶部通栏消失;再往上滑动到距离顶部一定距离,顶部通栏再次出现:该效果的关键点是比较当前滑动距离和自己设置的top值
- 滚动条往上滑动也会出现:该效果的关键点时比较上次滚动距离与当前距离
<style>
*{
margin:0px;
padding: 0px;
}
body{
height: 1200px;
}
h1{
text-align: center;
height: 0px;
background-color: pink;
font-size: 30px;
transition: height 0.5s 0s linear;//渐变效果
overflow: hidden;
width: 100%;
position: fixed;
}
p{
width: 50px;
height: 50px;
background-color: plum;
position: fixed;
right:30px;
bottom: 100px;
display: none;
}
</style>
<h1>顶部通栏</h1>
<p></p>
<script>
//获取操作对象
var h1=document.querySelector("h1")
var p1=document.querySelector("p")
var prevTop1 //上一次滚动距离
var top1 //滚动距离
var dsq
//给window对象绑定滚动事件
window.onscroll=function(){
//获取滚动距离
top1=document.documentElement.scrollTop
// console.log(prevTop1,top1)
//判断上一次滚动距离是否小于当前滚动距离
if(prevTop1<top1){
clearInterval(dsq)
}
//当滚动距离大于500,显示顶部通栏和按钮
if(top1>500){
h1.style.height='50px'
p1.style.display='block'
}
//当滚动距离小于300,隐藏顶部通栏和按钮
if(top1<300){
h1.style.height='0px'
p1.style.display='none'
}
prevTop1=top1
}
p1.onclick=function(){
dsq=setInterval(function(){
//判断当前滚动距离是否小于等于0
if(top1<=0){
clearInterval(dsq)
return
}
//重新设置滚动距离
document.documentElement.scrollTop=top1-30
},50)
}
</script>