vue js 獲取滾動距離 以及 返回頂部按鈕

ownlight發表於2020-10-29
  1. 獲取滾動距離 判斷是否回到頂部
  data() {
    return {
      scrollNum: 0, //滾動距離
      isTop: false, //是否顯示回到頂部按鈕
    };
  },
  mounted() {
    window.addEventListener("scroll", () => {
      let top =
        document.documentElement.scrollTop ||
        document.body.scrollTop ||
        window.pageYOffset;
      this.scrollNum = top;
      if (top >= 100) {
        this.isTop = true;
      } else {
        this.isTop = false;
      }
    });
  },
  1. 回到頂部按鈕 div
<!-- 回到頂部 -->
    <div
      class="goTop iconfont ml-gotop"
      :class="isTop ? 'goTopAfter' : ''" 
      @click="goTop()"
    ></div>
  1. 回到頂部方法
	goTop() {
      document.documentElement.scrollTop = 0;
    },
  1. 按鈕樣式
.goTop {
  position: fixed;
  bottom: -100px;
  right: 5%;
  width: 60px;
  height: 60px;
  border-radius: 30px;
  z-index: 10;
  background-color: rgba(33, 81, 129, 0.5);
  transition: 0.3s ease-in-out;
  font-size: 30px;
  text-align: center;
  line-height: 60px;
  color: #ffffff;
  transition: 0.3s ease-in-out;
  cursor: pointer;
}
.goTop:hover {
  background-color: rgba(33, 81, 129, 1);
  transition: 0.3s ease-in-out;
}
.goTopAfter {
  transition: 0.3s ease-in-out;
  bottom: 100px;
}

相關文章