天天看點

vue 回到頂部 backTop(自定義元件)

vue 回到頂部 backTop(自定義元件)

使用方式

使用參數

參數 類型 是否必填 預設 描述
topHeight Number 500 初始出現的高度
speed Number 10 初始傳回的速度
setSpeed Number 20 加速度
right Number 60 距離浏覽器右側的距離
bottom Number 80 距離遊覽器下面的距離

源代碼

<template>
  <div class="backTop" v-show="toTopShow" @click="handleToTop" 
  :style="{right: right + 'px', bottom: bottom +'px',}">
    <img src="../assets/img/up.png">
  </div>
</template>

<script>
  export default {
    data() {
      return {
        toTopShow: false,
        scrollTop: 0
      }
    },
    props: {
      // 開始出現的高度
      topHeight: {
        type: Number,
        default: 500
      },
      // 開始速度
      speed: {
        type: Number,
        default: 10
      },
      // 疊加速度
      setSpeed: {
        type: Number,
        default: 20
      },
      right: {
        type: Number,
        default: 60
      },
      bottom: {
        type: Number,
        default: 80
      }
    },
    mounted () {
      const self = this
      window.addEventListener('scroll', this.debounce(function () {
        self.handleScrolls()
      }, 300))
    },
    methods: {
      // 監控防抖
      debounce(fn, wait) {
        let timer = null
        return function () {
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(fn, wait)
        }
      },
      // 處理滾動條的監控
      handleScrolls() {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        this.scrollTop = scrollTop
        if (scrollTop > this.topHeight) {
          this.toTopShow = true
        } else {
          this.toTopShow = false
        }
      },
      // 處理回到開始位置
      handleToTop() {
        let speed = this.speed
        const setSpeed = this.setSpeed
        const self = this
        const timer = setInterval(function() {
          self.scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
          if (self.scrollTop > 0) {
            self.scrollTop = (self.scrollTop - speed > 0) ? (self.scrollTop - speed) : 0
            speed += setSpeed
            window.scrollTo(0, self.scrollTop)
          } else {
            clearInterval(timer)
          }
        }, 60)
      }
    }
  }
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
  .backTop {
    width: 60px;
    height: 60px;
    background-color: #2C2C2C;
    border-radius: 50%;
    position: fixed;
    /*right: 60px;*/
    /*bottom: 80px;*/
    text-align: center;
    padding-top: 2px;
    cursor: pointer;
    /* 動畫 */
    transition: 0.6s;
    img {
      text-align: center;
    }
  }
  .backTop:hover {
    background-color: #868880;
  }
</style>

           

如果感覺這篇文章對你有幫助,加個關注吧!!!

也可關注我的公衆号,我們一起交流。

vue 回到頂部 backTop(自定義元件)

繼續閱讀