滑动一段距离后实现吸顶的方式及坑点

需求:

滑动一段距离后固定在视口顶部,实现吸顶效果

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>

效果:
在这里插入图片描述

坑点:

  1. 父容器必须比要粘性定位的容器大,否则无法定位
  2. 需要有滚动的场景,即父容器比粘性定位大的场景,必须大于整个屏幕屏幕或者overflow: scroll;
  3. 至少设置一个属性:top,left,right,bottom

目前来说我对postion:sticky的尝试都是只能吸父亲元素的吸顶,没有实现跨级吸顶
所谓跨级吸顶,就是初始情况下,目标元素位于文档流的某一位置,距离页面视口一段距离,滚动后其吸顶祖先元素的顶

兼容情况参考

MDN

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值