[英]back-to-top button not appearing
Using Javascript, I've added a back-to-top button to my website.使用 Javascript,我在我的网站上添加了一个返回顶部按钮。 When I scroll, it appears (so the first function below works fine).
当我滚动时,它会出现(所以下面的第一个 function 工作正常)。 However, when I add the second function, the button doesn't even appear when I scroll.
但是,当我添加第二个 function 时,滚动时甚至不会出现该按钮。 I've been at this for hours?
我已经在这几个小时了? Have I missed something obvious?
我错过了什么明显的东西吗?
window.addEventListener("scroll", appear);
function appear(){
if (document.documentElement.scrollTop > 20)
{document.getElementById("button").style = "display: block;"}
else
{document.getElementById("button").style = "display: none;"}
};
document.getElementById("button").addEventListener("click", top);
function top(){
document.documentElement.scrollTop = 0
};
Edit:编辑:
html html
<img id="button" src="button.jpg" alt="the back-to-top button">
css css
#button {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 1;
height: 50px;
border-radius: 10px;
cursor: pointer;
}
Ok, so the issue here, I believe is that top
is already a property on window
and you are replacing it by creating a global function called top
.好的,所以这里的问题是,我相信
top
已经是window
上的一个属性,您正在通过创建一个名为top
的全局 function 来替换它。
This will work if you change your function to something like goToTop
.如果您将 function 更改为类似
goToTop
,这将起作用。
If you log console.log(window.top)
you'll find something already exists there.如果你记录
console.log(window.top)
你会发现那里已经存在一些东西。
window.addEventListener("scroll", appear);
function appear(){
if (document.documentElement.scrollTop > 20)
{document.getElementById("button").style = "display: block;"}
else
{document.getElementById("button").style = "display: none;"}
};
function goToTop(){
document.documentElement.scrollTop = 0
};
document.getElementById("button").addEventListener("click", goToTop);
Instead of代替
document.getElementById("button").style = "display: block;"
I think you should write我认为你应该写
document.getElementById("button").style.display = "block"
similar to the next one.类似于下一个。 I refer to this website - https://www.w3schools.com/jsref/prop_html_style.asp
我参考这个网站 - https://www.w3schools.com/jsref/prop_html_style.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.