我有一个“返回顶部”按钮,它在所有浏览器甚至移动设备上都非常适合我。因为我在基本上是照片库页面上使用它,最新的照片被添加到底部,我想添加一个始终在页面顶部可见的匹配按钮,以便经常访问者可以直接跳到底部。我搜索了 Stack 并发现了许多类似的问题,但因为我对 JavaScript 一无所知,所以我不知道如何将提供的解决方案转换为我的特定现有代码。
这是我的代码:
// When the user scrolls down 200px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
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;
}
#myBtn {
display: none; /* hidden by default */
position: fixed; /* sticky position */
bottom: 20px; /* distance from bottom */
right: 30px; /* distance from right */
z-index: 99;
border: 4px solid #0099ff;
border-radius: 20px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
outline: none;
background-color: #6b6b6b; /* GRAY */
color: #ffffff; /* WHITE text */
font-size: 13px;
font-weight: bold;
cursor: pointer; /* Add a mouse pointer on hover */
padding: 10px;
}
<button onclick="topFunction()" id="myBtn" title="Go to top of page">Top of Page</button>
谢谢你。