滚动返回顶部按钮
创建于 2024-12-03 /
29
字体:
[默认]
[大]
[更大]
了解如何使用 CSS 创建滚动"返回顶部"按钮。
如何创建滚动到顶部按钮
步骤 1) 添加 HTML:
创建一个按钮,当用户点击该按钮时,该按钮会将用户带到页面顶部:
实例
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>步骤 2) 添加 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; /* 在悬停时添加深灰色背景 */
}
Advertisement -->
步骤 3) 添加 JavaScript:
实例
//获取按钮: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; // For Chrome, Firefox, IE and Opera
} 亲自试一试 »
0 人点赞过