CSS position属性指定一个元素(动态的,绝对的,相对或固定)的定位办法,本文通过一个理论场景来剖析一下 fixed,sticky 的区别。

定义回顾

  • fixed 生成固定定位的元素,绝对于浏览器窗口进行定位。元素的地位通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
  • sticky 粘性定位,该定位基于用户滚动的地位。它的行为就像 position:relative; 而当页面滚动超出指标区域时,它的体现就像 position:fixed;,它会固定在指标地位。

场景形容

页面须要有一个工具条悬浮在容器顶部,别离应用fixed,sticky实现,如下图所示:

应用fixed定位发现fixed_bar超出了父级容器的宽度,如果你刚好是在这种状况下想让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>

总结

如果元素是窗口宽度的100%,且起始地位就是固定顶部或底部,那么fixed定位可能比拟适合。如果元素是要在父容器(小于窗口宽度)中滚动一段距离悬浮,那么应用sticky可能比拟容易。