我如何通过只使用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>
发布于 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新手,请查看:
使用以下命令将jQuery添加到您的HTML头:
<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‘是滚动动画的持续时间,单位为毫秒。
发布于 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
发布于 2021-11-19 19:53:05
只需像这样扩展您的scrollTop调用:
window.scrollTo({top: 0, behavior: 'smooth'});
https://stackoverflow.com/questions/70040193
复制相似问题