javascript - 如何使 "scroll to top"JS 函数在 JQuery 中变慢

标签 javascript html css

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

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

//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;
}
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;
}
<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>

最佳答案

为纯 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 head 中:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

并将您的 topFunction 替换为:

function topFunction() {
 
    $('html, body').animate({
        scrollTop: 0
      }, 500);
}

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

关于javascript - 如何使 "scroll to top"JS 函数在 JQuery 中变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70040193/

相关文章:

javascript - 当有多个带有数据请求的 React.js 组件实例时如何处理缓存?

javascript - 需要帮助使用 SharePoint 列表和 PSServices 将其他系列添加到 Highcharts 图表中

javascript - jQuery 中的链接替换了 HTML 不起作用

html - CSS :hover doesn't work with IE in SharePoint

javascript - 如何显示和映射状态或 const 数据数组对象的第一个 id?

javascript - 获取html标签的大小

html - 如何使溢出: hidden really hide content?

php - 被重定向到错误的地方 - 有时

css - WOOCOMMERCE 单品布局定制

javascript - 以父组件内对象的形式从所有子组件获取合并数据 : React JS