我的"返回顶部"按钮工作正常。然而,按钮显示在页面的顶部,我想在滚动20次后隐藏并显示。我用的是w3学校的例子。当我在代码中使用它时,这会引发错误。我该如何修复它?
Error
> (index):115 Uncaught TypeError: Cannot read property 'style' of null
at scrollFunction ((index):115)
at window.onscroll ((index):108)
scrollFunction @ (index):115
window.onscroll @ (index):108
这是我的CSS:
#myBtn {
width: 3rem;
height: 3rem;
align-items:center !important;
}
#myBtn svg {
fill: #000;
display: block !important;margin: auto !important;
}
我的Javascript如下:
/** Scroll back-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;
}
var url = window.location.href;
var index = url.lastIndexOf("/") + 1;
var filename = url.substr(index);
if (filename == "index.html") {
$("top").hide() ;
};
这是我定义按钮的HTML。
<button class="myBtn" type="button" aria-label="Back to Top" style="float:right;" onclick="topFunction()" id="myBtn">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 32 32" aria-hidden="true" style="will-change: transform;">
<path d="M16 14L6 24 7.4 25.4 16 16.8 24.6 25.4 26 24zM4 8H28V10H4z"></path></svg></button>
您已经在函数scrollFunction()
之外定义了变量mybutton
。尝试在函数中定义它,如下所示:
function scrollFunction() {
var mybutton = document.getElementById("mybtn")
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
或者将其作为这样的参数传入:
function scrollFunction(mybutton) {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
只有一个错误。只是改变
var mybutton = document.getElementById("top"); to
var mybutton = document.getElementById("myBtn");
除此之外,将display:none
添加到按钮中。因此,默认情况下不会显示。