vue实现页面滑动头部header固定栏背景渐变

因为代码是我自己要看的 所以我自己看得懂就好了哈哈~直接上代码(有注释)

<template>
  <div>
      <div class="header" :style="{background:color}">
              header
      </div>
      <div class="banner" id="searchBar">
          <ul>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
              <li>123</li>
          </ul>
      </div>
  </div>
</template>

<script>
export default {
    data()
    {
        return{
            color:"pink"
        }
    },
   mounted() {
    //首先,在mounted钩子window添加一个滚动滚动监听事件
    window.addEventListener("scroll", this.handleScroll);
  },
  methods: {
    //然后在方法中,添加这个handleScroll方法来获取滚动的位置
    handleScroll() {
      let scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      let offsetTop = document.querySelector("#searchBar").offsetTop;

      //设置背景颜色的透明读
      if (offsetTop && scrollTop) {
        this.color = `rgba(255, 255, 255,${scrollTop / (scrollTop + 40)})`;
      } else if (scrollTop == 0) {
        this.color = "white";
      }
      else if(scrollTop != 0)
      {
          this.color = "yellow";
      }
    }
  },
  //由于是在整个window中添加的事件,所以要在页面离开时摧毁掉,否则会报错
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  }
}
</script>

<style lang="scss" scoped>
.banner{
    width: 100%;
    height: 500px;
    background: red;
}
.header{
    width: 100%;
    height: 40px;
    background: white;
    position: fixed;
    left: 0;
    top: 0;
}
</style>

这种案例还是挺常见的比如在苏宁App上面
在这里插入图片描述
在这里插入图片描述

发布了39 篇原创文章 · 获赞 46 · 访问量 2811

猜你喜欢

转载自blog.csdn.net/sslcsq/article/details/104750670