如何创建:返回页面顶部的按钮
学习如何使用 CSS 创建“滚动回到顶部”按钮。
如何创建滚动到顶部按钮
第一步 - 添加 HTML:
创建一个按钮,单击该按钮会将用户带到页面顶部:
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
第二步 - 添加 CSS:
设置按钮的样式:
#myBtn { display: none; /* 默认是隐藏的 */ position: fixed; /* 固定/粘性定位 */ bottom: 20px; /* 将按钮置于页面底部 */ right: 30px; /* 将按钮置于距离页面右侧 30px 处 */ z-index: 99; /* 确保它不重叠 */ border: none; /* 删除边框 */ outline: none; /* 删除轮廓 */ background-color: red; /* 设置背景色 */ color: white; /* 文本颜色 */ cursor: pointer; /* 添加鼠标悬停时的鼠标指针 */ padding: 15px; /* 一些内边距 */ border-radius: 10px; /* 圆角 */ font-size: 18px; /* 增加字体大小 */ } #myBtn:hover { background-color: #555; /* 鼠标悬停时添加深灰色背景 */ }
第三步 - 添加 JavaScript:
// 获取按钮: let mybutton = document.getElementById("myBtn"); // 当用户从文档顶部向下滚动 20px 时,显示该按钮 window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { mybutton.style.display = "block"; } else { mybutton.style.display = "none"; } } // 当用户单击按钮时,滚动回文档顶部 function topFunction() { document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // 适用于 Chrome、Firefox、IE 和 Opera 浏览器 }