【Vue一键回到top down】

<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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值