【发布时间】:2017-12-26 08:56:55
【问题描述】:
我的页面上有一个滚动到顶部的按钮,但是当我单击它时,它不会滚动到顶部,它只是将我直接带到顶部,就像我加载了一个新页面一样,但我需要的是滚动动画。
javascript
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").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;
}
css
#myBtn {
display: none;
position: fixed;
bottom: 50px;
right: 20px;
z-index: 99;
border: teal;
outline: none;
background-color: #FF6347;
color: white;
cursor: pointer;
padding: 0px;
border-radius: 100px;
width: 40px;
height: 40px;
}
#myBtn i {
width: 40px;
height: 40px;
text-align: center;
z-index: 100;
line-height: 40px;
color: white;
}
#myBtn:hover {
background-color: #FF6320;
}
html
<button1 onclick="topFunction()" id="myBtn" title="Go to top"><i class="fa fa-angle-double-up" aria-hidden="true"></i></button1>
【问题讨论】:
-
stackoverflow.com/questions/17733076/… 的可能重复项,这可能是您想知道的解决方案。
-
您在 scrolltop 函数中缺少动画过程。现在它只是按照功能应该做的那样跳起来。应用一个动画来添加它。
-
如果你使用 jQuery:stackoverflow.com/questions/16475198/…
-
@Markus 这个问题很模糊,并且可以接受任何答案,而不是具体的 JavaScript,我之前已经解决过这个问题和其他问题,但还没有找到我想要的东西,因此为什么我提供了与我的具体问题相关的代码。谢谢
-
@SumnerEvans 我以前从未接触过 jquery
标签: javascript html