所以,我现在正在构建一个网站,并且我设置了一个按钮,当您向下滚动一小段距离时它应该出现,当您单击它时,它会将您带到页面顶部。但由于某种原因,该按钮始终可见,即使我在顶部,这是我的代码:
document.getElementById("scrollButton").onclick = goToTop();
window.onscroll = function() {
"use strict";
scrollFunction();
};
function scrollFunction() {
"use strict";
if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
document.getElementById("scrollButton").style.display = "block";
} else {
document.getElementById("scrollButton").style.display = "none";
}
}
function goToTop() {
"use strict";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
.scrollButton {
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;
}
.scrollButton:hover {
background-color: #555;
}
#fill {
height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>
我不确定哪里出了问题,在 javascript 中的“scrollFunction()”中,它说当我向下滚动时,它应该使它出现,但是当我在顶部时,它应该消失,但它没有。有人知道为什么吗?
最佳答案
您需要默认设置display:none
。
document.addEventListener('DOMContentLoaded', function() {
scrollFunction();
})
document.getElementById("scrollButton").onclick = goToTop;
window.onscroll = function() {
"use strict";
scrollFunction();
};
function scrollFunction() {
"use strict";
if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
document.getElementById("scrollButton").style.display = "block";
} else {
document.getElementById("scrollButton").style.display = "none";
}
}
function goToTop() {
"use strict";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
.scrollButton {
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;
}
.scrollButton:hover {
background-color: #555;
}
#fill {
height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>
关于Javascript > HTML 滚动按钮在页面顶部时不会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855556/