吸顶效果
1. 采用 position:sticky 粘性定位
这是一个结合了 position:relative 和 position:fixed 两种定位功能于一体的特殊定位,适用于一些特殊场景;元素定位表现为在触发条件前为相对定位,触发条件之后为固定定位
top, right, bottom,left 就是条件;跨越它们设定的值,就是触发条件
设置的top、left的值等就是相当于设置fixed定位的位置
兼容性:position:sticky 的兼容性不乐观
案例:
//html
<body>
<div class="box">
<nav>我是顶部</nav>
<div class="content">
<div class="item"> 我是第一段 </div>
<div class="item"> 我是第二段 </div>
<div class="item"> 我是第三段 </div>
</div>
</div>
</body>
//css
.box{
width: 100%;
height: 1500px;
}
nav{
width: 100%;
height: 60px;
background-color: cornflowerblue;
line-height: 60px;
color: cornsilk;
text-align: center;
font-size: 24px;
//position: sticky; 定位
position: -webkit-sticky;
position: sticky;
top: 0;
}
当nav相对于浏览器窗口top为0时,nav 就一直固定在顶部,就是nav变成fixed定位,top为0
生效规则
- 须要有top, right, bottom,left 四个阈值其中之一;并且 top 和 bottom 同时设置时,top 生效的优先级高,left 和 right 同时设置时,left 的优先级高
- 设定为 position:sticky 元素的任意父节点的 overflow 属性必须是 visible;否则不生效;我实际测试,父元素必须要为visible,祖父级元素overflow设置为scroll,也能生效;但是最好祖父级、父级overflow都设置为visible,即默认值
- 父级元素我测了一下,position:absolute/relative ; 也能生效,但是fixed就不能生效了
- sticky 是容器相关的,也就说 sticky 的特性只会在他所处的容器里生效。
举例说明:
我现在想让section 使用sticky 让section固定在顶部(top:0);我在往下滚动时,只要div.content这个容器没有超出浏览器视图窗口,就能看到section固定在顶部,但是只要div.content这个容器被卷上去了,就是它没有在浏览器视图窗口中了,里面的section也不能固定在顶部了
2. 监听滚动条
window.addEventListener("scroll", function(){
//滚动条的位置
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
xxxx
})