实现一个简单的返回顶部示例

思路:要实现一个点击后能返回顶部的按钮,首先得创建一个容器,并需要设置它的style{overflow : auto}。然后,我们需要给容器添加一个监听器,监听滚动事件,当容器的scrollTop大于某个值时,显示出这个按钮。最后给这个按钮添加一个监听器,当按钮被点击的时候,将容器的scrollTop设为0。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>返回顶部示例</title>
  <style>
    .scroll-container {
      height: 300px;
      overflow: auto;
      border: 1px solid #ccc;
    }

    .content {
      height: 600px;
      background-color: #f0f0f0;
    }

    .scroll-btn {
      margin-top: 10px;
      padding: 5px 10px;
      background-color: #007bff;
      color: white;
      border: none;
      cursor: pointer;
    }

    .visible {
      display: block;
    }

    .invisible {
      display: none;
    }
  </style>
</head>
<body>
  <div id="scrollContainer" class="scroll-container">
    <div id="content" class="content">
      <!-- 长内容 -->
    </div>
  </div>
  <button id="scrollToTopBtn" class="scroll-btn invisible">返回顶部</button>

  <script>
    const scrollContainer = document.getElementById('scrollContainer');
    const content = document.getElementById('content');
    const scrollToTopBtn = document.getElementById('scrollToTopBtn');

    scrollContainer.addEventListener('scroll', () => {
      const scrollTopPosition = scrollContainer.scrollTop;
      if (scrollTopPosition > 100) {
        scrollToTopBtn.classList.remove('invisible');
      } else {
        scrollToTopBtn.classList.add('invisible');
      }
    });

    scrollToTopBtn.addEventListener('click', () => {
      scrollContainer.scrollTop = 0;
    });
  </script>
</body>
</html>

代码中有一些关键属性,想深入学习的朋友我这里提供几个链接

scrollTop、clientHeight和scrollHeight  scrollTop、clientHeight和scrollHeight

getBoundingClientRect()  Element.getBoundingClientRect()

scrollTo()  Element.scrollTo()

猜你喜欢

转载自blog.csdn.net/weixin_55020138/article/details/132389207