<template>
  <div>
    <div class='content' ref='content'>
      <!-- 内容区域 -->
    </div>
    <button class='scroll-button' v-show='showButton' @click='scrollToTop'>
      返回列表
    </button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showButton: false
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      // 获取内容区域的高度
      const contentHeight = this.$refs.content.offsetHeight;
      // 获取滚动条的位置
      const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      // 判断是否显示按钮
      this.showButton = scrollTop > contentHeight;
    },
    scrollToTop() {
      // 滚动到顶部
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
  }
};
</script>

<style>
.content {
  height: 2000px; /* 内容区域的高度,用于测试滚动效果 */
}

.scroll-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 40px;
  height: 20px;
  background-color: blue;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>

这段代码使用Vue组件实现了一个简单的'返回顶部'按钮,并具有以下功能:

  • 跟随滚动条滚动: 当页面向下滚动时,按钮会始终保持在页面右下角的固定位置。
  • 动态显示: 当页面滚动到一定高度后,按钮才会显示,否则保持隐藏状态。
  • 平滑滚动: 点击按钮后,页面会平滑地滚动到顶部。

你可以根据自己的需求修改按钮的样式、内容和触发显示的高度。

Vue实现跟随滚动条的返回顶部按钮

原文地址: https://www.cveoy.top/t/topic/fS1I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录