position
分类
值 | 中文名 | 脱离文档流 | 说明 |
---|---|---|---|
static | 静态定位 | 否 | 默认行为 |
relative | 相对定位 | 否 | 相对原有位置进行定位 |
absolute | 绝对定位 | 是 | 向上查找第一个非 static 定位的元素,以此作为基准进行定位; |
fixed | 固定定位 | 是 | 相对于浏览器窗口进行定位;一般用于顶部导航栏等 |
sticky | 粘性定位 | 否 | 类似 relative 与 fixed 结合体,滚动到对应阈值时会变为类似 fixed 属性; |
问题
1. 说说 position 有哪些值,分别是做什么的?
查看上面表格,特表要说明的是 sticky
值:sticky
实现粘性定位,类似 relative
与 fixed
结合体,滚动到对应阈值时会变为类似 fixed
属性,比如在滚动到顶部时固定的导航栏场景中,我们只需要设置对应固定的 top
值即可,而传统做法需要监听滚动事件,根据滚动高度对导航栏进行 fixed 与 static 值的切换,且 fixed 会脱离文档流,需要对菜单栏外层设置包裹元素进行占位。
2. 如何实现左侧导航栏滚动吸顶效果?
假设导航栏距离顶部 100px
:
2.1 通过滚动事件计算导航栏距离顶部距离实现
当页面滚动时,如果滚动条距离顶部的值 (scrollTop
) ≥ 导航栏距离顶部距离,则将元素 position: fixed;
否则设置为 position: static;
。
例子:
HTML
<!-- 外层包裹占位元素,防止 fixed 脱离文档流时空间被占据 -->
<div class="nav-wrap">
<div class="nav">
</div>
</div>
<!-- 外层包裹占位元素,防止 fixed 脱离文档流时空间被占据 -->
<div class="nav-wrap">
<div class="nav">
</div>
</div>
JS
window.addEventListener('scroll', handleScroll)
function handleScroll() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}
window.addEventListener('scroll', handleScroll)
function handleScroll() {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}
2.2 使用 position: sticky
实现
css
.nav {
position: sticky;
top: 100;
}
.nav {
position: sticky;
top: 100;
}