【发布时间】:2020-10-03 04:25:04
【问题描述】:
我有以下从 w3schools 获得的简单 scrollTop() 函数。我遇到的问题是设置滚动时间。不同的人给出了不同的方法,每个人都从以下代码中删除了一行或所有行。我正在等待一个可以添加来设置滚动速度并且不会删除其他文本的功能。这是代码笔工作https://codepen.io/vkdatta27/pen/zYqQbmM
var mybutton = document.getElementById("myBtn");
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;
}
html {
scroll-behavior: smooth
}
<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>
【问题讨论】:
-
查看scrollTo函数,设置行为:'smooth',你需要确认你需要的浏览器兼容性:developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo
-
@LahiruTM,我已经看到了。但我已经提到我只想在以下代码中添加内容。 Cam 你在下面的代码中添加了一些东西吗?
-
@emiliokyp,
scroll behavior: smooth已添加到 css 中。我想控制它的时间。看,例如,滚动顶部功能需要在 8 秒内发生 -
在脚本部分加载 Jquery。然后在顶部函数中注释两行并将其放入。 $('html,body').animate({ scrollTop: 0 }, 'slow');
标签: javascript html jquery css