标签搜索

javascript 返回顶部实例

sunshine
2024-08-02 / 0 评论 / 17 阅读
温馨提示:
本文最后更新于2024年08月05日,已超过42天没有更新,若内容或图片失效,请留言反馈。

平滑滚动到顶部样例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>返回顶部示例</title>
 <!-- 回到顶部 -->
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    /* 样式部分 */
    html {
      scroll-behavior: smooth; /* 平滑滚动 */
    }

    #backToTop {
      display: none; /* 初始隐藏 */
      position: fixed; /* 固定位置 */
      bottom: 30px; /* 距离底部30px */
      right: 30px; /* 距离右边30px */
      z-index: 99; /* 确保按钮在最前面 */
      font-size: 18px;
      background-color: #555; /* 按钮背景色 */
      color: white; /* 按钮文字颜色 */
      border: none; /* 无边框 */
      outline: none; /* 无外边框 */
      cursor: pointer; /* 鼠标悬停时变为指针 */
      padding: 15px; /* 按钮内边距 */
      border-radius: 10px; /* 圆角 */
    }

    #backToTop:hover {
      background-color: #000; /* 鼠标悬停时按钮背景色 */
    }
  </style>
</head>
<body>
<div class="test" style="width: 100%; height: 2000px; background-color: #f2f2f2;"></div>
<button id="backToTop" onclick="topFunction()">返回顶部</button>

<script>
    // 获取按钮
    var mybutton = document.getElementById("backToTop");

    // 当用户向下滚动 20px 出现按钮
    window.onscroll = function () {
        scrollFunction()
    };

    function scrollFunction() {
        if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
            mybutton.style.display = "block";
        } else {
            mybutton.style.display = "none";
        }
    }

    // 点击按钮,返回顶部
    function topFunction() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth' // 平滑滚动
        });
    }
</script>
</body>
</html>
感觉很棒,欢迎点赞 OR 打赏~
1
分享到:

评论 (0)

取消