javascript - Javascript > HTML 滚动按钮在页面顶部时不会消失
问题描述
所以,我现在正在建立一个网站,并且我设置了一个按钮,当你向下滚动一小段距离时它应该会出现,当你点击它时,它会将你带到页面顶部。但是由于某种原因,该按钮始终可见,即使我在顶部,这是我的代码:
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>
推荐阅读
- r - 从 terra 为 c 函数添加前缀
- python - The difference of loading model parameters between load_state_dict and nn.Parameter in pytorch
- go - Error get all list items deleted_at is not null
- hybris - Promoting items on Adaptive Search not working Hybris
- node.js - 上传到 S3 的图像已损坏
- python - 如何正确设置此线程套接字读取?
- integration-testing - 使用无服务器离线和集成测试进行模拟
- javascript - 与 Webpack 一起使用的 Vue 从 DOM 中删除应用程序根
- c++ - C++ 查找/子字符串错误
- c++ - 可以从具有相同名称的派生类函数调用基类函数。但我找不到支持这一点的标准报价