需求:
滑动一段距离后固定在视口顶部,实现吸顶效果
JS:判断滚动距离后固定定位
适用于无论多少层级的吸顶
先上代码:
window.onscroll = function () {
let topScroll = document.body.scrollTop || document.documentElement.scrollTop //兼容
//这里86仅举例
if (topScroll >= 86 ) {
//滚动超过多少为固定定位
settingRef.current.style.position = 'fixed'
settingRef.current.style.top = '0'
return
}
if (topScroll < 86 ) {
//鼠标回滚,缩小与视口距离的样式
settingRef.current.style.position = 'relative'
settingRef.current.style.top = '0'
}
}
css3新增的定位postion:sticky
是相对定位与固定定位的结合,距离相对元素多少像素后固定定位
适用于相对于父元素的吸顶(ps:慢慢尝试多级元素,若有误,望指出)
如果你设置了top: 30px,那么使用sticky的元素到达距离的父元素顶部30px的位置时变成固定定位
屏幕内实现吸顶:
<style>
.box {
position: -webkit-sticky;
position: sticky;
width: 100%;
height: 30px;
text-align: center;
color: #fff;
margin-bottom: 50px;
top: 0;
z-index: 1;
background: #007bff;
}
</style>
<body>
<div class="box">box1</div>
<div style="height:2700px;background-color: pink;">底部</div>
</body>
效果:
小容器内实现吸顶
<style>
.father {
width: 300px;
height: 500px;
background-color: wheat;
overflow: scroll;
}
.son1 {
height: 30px;
}
.son2 {
width: 300px;
height: 30px;
background-color: orange;
position: sticky;
top: 0
}
.son3 {
width: 300px;
height: 1000px
}
</style>
<body>
<div class="father">
<div class="son1"></div>
<div class="son2">头部</div>
<div class="son3">好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字好多字字
</div>
</div>
</body>
效果:
坑点:
- 父容器必须比要粘性定位的容器大,否则无法定位
- 需要有滚动的场景,即父容器比粘性定位大的场景,必须大于整个屏幕屏幕或者overflow: scroll;
- 至少设置一个属性:top,left,right,bottom
目前来说我对postion:sticky的尝试都是只能吸父亲元素的吸顶,没有实现跨级吸顶
所谓跨级吸顶,就是初始情况下,目标元素位于文档流的某一位置,距离页面视口一段距离,滚动后其吸顶祖先元素的顶