首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JQuery中让“滚动到顶部”JS函数变慢

如何在JQuery中让“滚动到顶部”JS函数变慢
EN

Stack Overflow用户
提问于 2021-11-19 19:47:07
回答 3查看 58关注 0票数 3

我如何通过只使用JQuery来编辑W3学校的这段代码,使其滚动速度变慢?它目前只是跳到顶部。有没有办法让它慢下来,这样用户就可以看到他们实际上是回到了页面的顶部?理想情况下,如果可能的话,整个东西都应该在JQuery中。

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_scroll_to_top

代码语言:javascript
运行
复制
//Get the button
var mybutton = document.getElementById("myBtn");

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};

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

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
代码语言:javascript
运行
复制
body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
}

#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  font-size: 18px;
  border: none;
  outline: none;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

#myBtn:hover {
  background-color: #555;
}
代码语言:javascript
运行
复制
<body>

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible 
  <strong>when the user starts to scroll the page</strong>.</div>

EN

回答 3

Stack Overflow用户

发布于 2021-11-19 20:12:26

用于纯jQuery的编辑

您正在寻找jQuery .animate()方法。查看:

https://www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

他们正在使用this.hash找到平滑滚动的目的地。您可以省略它,并将其替换为“0”以滚动到顶部。如果您是this.hash新手,请查看:

How does $(this.hash) work?

使用以下命令将jQuery添加到您的HTML头:

代码语言:javascript
运行
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

并将您的topFunction替换为:

代码语言:javascript
运行
复制
function topFunction() {
 
    $('html, body').animate({
        scrollTop: 0
      }, 500);
}

'500‘是滚动动画的持续时间,单位为毫秒。

票数 2
EN

Stack Overflow用户

发布于 2021-11-19 19:51:01

您可以尝试在smooth behavior https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo#examples中使用scrollTo

虽然它在Safari上不起作用(我看到它只在Safari14和更高版本中起作用),但对于Safari,你需要添加一个polyfill https://github.com/iamdustan/smoothscroll

票数 0
EN

Stack Overflow用户

发布于 2021-11-19 19:53:05

只需像这样扩展您的scrollTop调用:

代码语言:javascript
运行
复制
window.scrollTo({top: 0, behavior: 'smooth'});
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70040193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档