Vue 自定义滚轮 回到顶部/回到底部

239 阅读1分钟
<template>
  <div class="wraper" @mousewheel="scrollChange" ref="scrollview">
    <div id="topTarget"></div>

    <button
       id="test"
       style="position: fixed; right: 0; bottom: 30px"
       @click="toTop"
       v-show="isScroll"
    >
      回到顶部
    </button>

    <button
       id="test"
       style="position: fixed; right: 0; bottom: 0"
       @click="toBottom"
    >
      回到底部
    </button>

    <div v-for="(item, i) in 10000" :key="i">返回顶部</div>
    <div id="bottomTarget"></div>
  </div>

</template>
<script>
export default {
  data() {
    return {
      scroll: "",
      isScroll: false,
    };
  },
  mounted() {
    // 获取指定元素
    const scrollview = this.$refs["scrollview"];
    // 添加滚动监听,该滚动监听了拖拽滚动条
    // 尾部的 true 最好加上,我这边测试没加 true ,拖拽滚动条无法监听到滚动,加上则可以监听到拖拽滚动条滚动回调
    scrollview.addEventListener("scroll", this.scrollChange, true);
  },
  beforeDestroy() {
    // 获取指定元素
    const scrollview = this.$refs["scrollview"];
    // 移除监听
    scrollview.removeEventListener("scroll", this.scrollChange, true);
  },
  methods: {
    // 滚动监听,滚动到一定距离才出现回到顶部的按钮
    scrollChange(e) {
      console.log("滚动中", e.offsetY);
      if (e.offsetY > 50) {
        this.isScroll = true;
      }
    },
    toTop() {
      topTarget.scrollIntoView();
    },
    toBottom() {
      bottomTarget.scrollIntoView();
    },
  },
};
</script>
<style>
.wraper {
  width: 1000px;
  height: 100px;
  overflow-x: hidden;
  overflow-y: auto;
  background: #000;
  position: relative;
}
</style>