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定位可以完美满足你的要求,这应该是它出现的原因。

something...fixed_barcontent...something...sticky_barcontent...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'}}}}.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;}