CSS position定位(fixed、sticky)

CSS position 属性用于指定一个元素在文档中的定位方式。top,right,bottom 和 left 属性则决定了该元素的最终位置。CSS position属性默认为 静态static,除此之外还有相对定位relative,绝对定位absolute,固定定位fixed,粘性定位sticky。本文通过一个实际场景来分析一下 fixed,sticky 的区别。

fixed 生成固定定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。

sticky 粘性定位,该定位基于用户滚动的位置(原来的位置)。它的行为就像 position:relative; 它会悬浮在目标位置。

如果定位的元素是以窗口为参照,那么fixed定位可能比较合适;如果元素是要在父容器(一般小于窗口宽度)中滚动一段距离悬浮,那么使用sticky可能比较容易。

场景描述

页面需要有一个工具条-fixed_bar,当容器内部向上滚动时需要悬浮在容器顶部,分别使用fixed,sticky实现,如下图所示:

使用fixed定位发现fixed_bar超出了父级容器的宽度(即使已经设置fixed_bar的宽度为父级的100%),如果想让fixed_bar宽度为父级的100%,而且父级容器在向上滚动的时候,你还需要在scroll事件中动态改变fixed_bar的top值 —— 可谓“麻烦的一匹”。反观sticky定位可以完美满足你的要求,这应该是它出现的原因。

<template>
    <div>
        <div class="p_wrapper" @scroll="handleScroll">
            <div style="height: 50px;line-height: 50px;background-color: rgba(227,92,64,0.72)">
                something...
            </div>
            <div class="fixed_bar">
                fixed_bar
            </div>
            <div style="height: 1000px;line-height: 1000px;background-color: rgba(12,65,40,0.32);">
                content...
            </div>
        </div>
        <div class="p_wrapper">
            <div style="height: 50px;line-height: 50px;background-color: rgba(227,92,64,0.72)">
                something...
            </div>
            <div class="sticky_bar">
                sticky_bar
            </div>
            <div style="height: 1000px;line-height: 1000px;background-color: rgba(12,65,40,0.32);">
                content...
            </div>
        </div>
    </div>
</template>
<script>
export default {
    name: "position",
    mounted() {
        this.fixed = document.querySelector('.fixed_bar')
    },
    data() {
        return {
            fixed: '' // fixed_bar
        }
    },
    methods: {
        handleScroll(e) {
            console.log(e.target.scrollTop, this.fixed.style.top)
            if (e.target.scrollTop > 50) {
                this.fixed.style.top = '50px'
            } else {
                this.fixed.style.top = 100 - e.target.scrollTop + 'px'
            }
        }
    }
}
</script>

<style scoped>
.p_wrapper {
    box-shadow: 0 0 8px 3px rgba(0, 0, 0, 0.15);
    width: 70%;
    margin: 50px auto;
    max-height: 300px;
    overflow-y: auto;
    text-align: center;
    color: #fff;
}

.fixed_bar {
    height: 50px;
    background-color: rgba(111, 66, 193, 1);
    line-height: 50px;
    position: fixed;
    top: 100px;
    width: 100%;
}

.sticky_bar {
    height: 50px;
    background-color: rgba(111, 66, 193, 1);
    line-height: 50px;
    position: sticky;
    top: 0;
}
</style>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值