目录

1、通俗易懂

2、sticky介绍

3、举例(Vue2为例)


1、通俗易懂

  • position:sticky可以简单理解为是static和fixed的结合;
  • 可理解为在父元素滑动过程中,子元素距离其父元素的距离达到 sticky 粘性定位的要求时(如top:40px);position:sticky这时的效果相当于fixed定位,固定到适当位置。

2、sticky介绍

  • sticky只能在最接近的父元素为overflow中使用;
  • 至少规定top, left ,right, bottom中的一种, 否则stikcy定位不生效,最终效果类似于relative;
  • 假设定义了top(bottom)属性. 那么父元素height不能低于top(bottom)的值;
  • 使用前请检查兼容性

3、举例(Vue2为例)

如上图二:滑动后,红色div脱离原本的蓝色框所在文档流,最终悬浮在父容器top:40px处

 

<template>
  <div class="box">
    <div class="box-scroll">
      <div v-for="(item, index) in 10" :key="index">{{ index + 1 }}</div>
      <div class="box-scroll-sticky">我要悬浮在40px处</div>
      <div v-for="(item, index) in 100" :key="index">{{ index + 1 }}</div>
    </div>
  </div>
</template>
<script>
export default {};
</script>
<style lang="scss" scoped>
.box {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  &-scroll {
    height: 400px;
    width: 400px;
    background: #eee;
    overflow: auto; //父元素必须是scroll
    display: flex;
    flex-direction: column;
    position: relative;
    > div {
      width: 100%;
      height: 40px;
      border-bottom: 2px solid #fff;
    }
    &-sticky {
      position: sticky;
      top: 40px; //至少设置一个
      background: red;
      color: #fff;
    }
  }
}
</style>

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐