返回顶部按钮代码
时间: 2023-07-02 13:04:19 浏览: 83
你可以在 HTML 文件中添加以下代码,以创建一个“返回顶部”按钮:
```html
<button onclick="topFunction()" id="myBtn" title="回到顶部">返回顶部</button>
<script>
// 当页面滚动到一定位置时,显示“返回顶部”按钮
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// 点击“返回顶部”按钮时,回到页面顶部
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
```
在 CSS 文件中,你可以设置按钮的样式:
```css
#myBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: #555;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #777;
}
```