天天看點

vue 頂部導航監聽滾動條漸變效果

直接上代碼

HTML:

<header id="fixedBar" :style="style">
      <div  :style="{fontSize:'16px'}">
       導覽列裡的内容
      </div>
</header>
           

引入lodash (主要是為了做節流(throttle)或去抖(debounce))

import _ from 'lodash'
           

data:

data() {
      return {
        style: {},
        opacity: 0,
        offsetTop:0,
        }
      }
           

methods:

methods: {
      handleScroll:_.throttle( function () {
        var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        this.opacity = Math.abs(Math.round(scrollTop)) / 250;
        this.style = {background: `rgba(26, 212, 115,${this.opacity})`}
      },100),
      destroyed () {
        window.removeEventListener('scroll', this.handleScroll); // 離開頁面 關閉監聽 不然會報錯
      }
    },
           

mounted:

mounted(){
      this.offsetTop = document.querySelector('#fixedBar').offsetTop;
      // 開啟滾動監聽
      window.addEventListener('scroll', this.handleScroll);
    },
           

css:

#fixedBar {
      position: fixed;
      top: 0;
      z-index: 999;
      width: 100%;
      padding: 10px 15px;
    }
           

我是參考了兩篇文章寫出來的,下附連結:

參考文獻

https://blog.csdn.net/u014027680/article/details/79291096

–作者:Oceanic_Kang

https://www.cnblogs.com/haonanZhang/p/6994153.html

–作者:haonanElva