css:高级感满满的视差滚动效果

840 阅读1分钟

效果

动图.gif

通过css+js实现

<template>
  <h1 class="mountain">MOUN</h1>
</template>
<script>
export default {
  mounted() {
    this.roll()
  },
  methods: {
    roll() {
      const mountain = document.querySelector('.mountain')
      document.addEventListener('scroll', () => {
        const scrollTop = document.documentElement.scrollTop
        if (scrollTop)
          mountain.style.backgroundPosition = `calc(50% + ${scrollTop}px) calc(50% + ${scrollTop}px)` // 动态改变背景定位的偏移量
      })
    }
  }
}
</script>
<style lang="less" scoped>
.mountain {
  height: 200vh;
  background-image: url('./images/mountain.jpg');
  background-size: cover;
  background-position: center; // center 相当于 50% 50%
  -webkit-background-clip: text; /* 文字之外的区域被裁减掉 */
  position: relative;
  padding: 100px;
  color: transparent;
  font-size: 26vw;
  text-align: center;
  user-select: none; /* 禁止选中文字 */
  &::before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: -1;
    background-image: inherit;
    background-size: inherit;
    background-position: center;
  }
}
</style>

分析

  1. 结构:上下两层结构,都是同一个背景图,通过定位将两张图片重叠
  2. js:由于document内部的mountain盒子高度为200vh,所以可以监听到document文档的滚动,拿到向上卷曲出去的距离,赋值给mountain盒子的bgP。此时文字的背景图发生偏移,而before中的图片是不动的,形成视差滚动效果

所需图片

gitee.com/wuqilang/vu…

参考

www.bilibili.com/video/BV1dR…