【问题标题】:How to make HTML page scroll all the way up when clicking a button? [duplicate]单击按钮时如何使HTML页面一直向上滚动? [复制]
【发布时间】:2021-04-09 23:32:06
【问题描述】:

所以我的 HTML 页面中有以下内容:

我故意这样做,以便发生“溢出”,从而导致右侧的滚动条。

所以我制作了一个名为“单击以向上滚动”的按钮。所以我想要的是,每次我们点击那个按钮时,文档都会立即向上滚动。这意味着如果我一直向下导航,然后单击按钮,它会一直向上。

我查了一下,有一个方法“scrollTop”,但它似乎不起作用。希望能得到一些帮助。

document.getElementById("scrollup").addEventListener("click", scrollUpmost);

function scrollUpmost() {
    $(document).scrollTop();
}
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    height: 100%;
}

.container {
    border: 1px solid orange;
}

.big_div {
    border: 1px solid black;
    height: 1200px;

}

#scrollup {
    margin-top: 900px;
}
<!DOCTYPE html>
<html lang="en">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div class = "big_div">
      <button id = "scrollup">Click to scroll up</button>
    </div>
  </div>
  <script src = "test.js"></script>
</body>
</html>

【问题讨论】:

  • 您只需在滚动函数window.scrollTo({ top: 0, behavior: 'smooth' }); 中添加这一行@

标签: javascript html css


【解决方案1】:

$("#scrollup").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});
    * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html, body {
    height: 100%;
}

.container {
    border: 1px solid orange;
}

.big_div {
    border: 1px solid black;
    height: 1200px;

}

#scrollup {
    margin-top: 900px;
}
  
<!DOCTYPE html>
<html lang="en">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  
  <div class="container">
    <div class = "big_div">
      <button id = "scrollup">Click to scroll up</button>
    </div>
  </div>
  <script src = "test.js"></script>
</body>
</html>

请试试这个代码

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多