vue 向下滑动显示返回按钮,点击按钮返回顶部示例

<!-- 返回顶部按钮示例 -->
<template>
    <div>
      <div
        ref="scrollContainer"
        style="overflow-y: auto; height: 200px; position: relative;"
        @scroll="checkScroll"
      >
        <!-- 这里是长内容 -->
        <p v-for="i in 100" :key="i">这是第 {{ i }} 行内容</p>
      </div>
      <button v-if="showButton" @click="scrollToTop" style="position: absolute; bottom: 10px;">
        回到顶部
      </button>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        showButton: false,
        scrollThreshold: 100 // 滚动阈值
      };
    },
    methods: {
      checkScroll() {
        const scrollTop = this.$refs.scrollContainer.scrollTop;
        this.showButton = scrollTop > this.scrollThreshold;
      },
      scrollToTop() {
        this.$refs.scrollContainer.scrollTop = 0;
      }
    },
    mounted() {
      // 初始化时调用一次,确保按钮的初始状态
      this.checkScroll();
    }
  };
  </script>
  
  <style scoped>
  /* 添加一些样式使按钮更好看 */
  button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    right: 10px; /* 距离右边10px */
    bottom: 10px; /* 距离底部10px */
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
  }
  </style>

展示效果如下图:

点击按钮后,回到顶部

相关推荐

  1. web页面右键显示按钮

    2024-03-25 00:06:01       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-25 00:06:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-25 00:06:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-25 00:06:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-25 00:06:01       20 阅读

热门阅读

  1. a为何值是下面代码输出“成立“

    2024-03-25 00:06:01       17 阅读
  2. 01-Pandas的方法介绍

    2024-03-25 00:06:01       16 阅读
  3. 定义了服务器的端口号和Servlet的上下文路径

    2024-03-25 00:06:01       20 阅读
  4. OpenCV支持哪些类型的文件格式读写?

    2024-03-25 00:06:01       18 阅读
  5. 周报_第四十六周

    2024-03-25 00:06:01       15 阅读
  6. Spring Cloud微服务功能及其组件详细讲解

    2024-03-25 00:06:01       17 阅读
  7. ES6—运算符的扩展

    2024-03-25 00:06:01       17 阅读
  8. python 模块与包

    2024-03-25 00:06:01       16 阅读
  9. 日期时间api

    2024-03-25 00:06:01       22 阅读