以下是一个简单的HTML代码示例,用于创建一个页面返回顶部的按钮:
<!DOCTYPE html>
<html lang="en">
<head>
<meta ch****t="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Back to Top Button</title>
<style>
#back-to-top {
display: none;
position: fixed;
bottom: 20px;
right: 20px;
background-color: #3498db;
color: #fff;
width: 50px;
height: 50px;
text-align: center;
line-height: 50px;
border-radius: 50%;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition: background-color 0.3s;
}
#back-to-top:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<button id="back-to-top" onclick="scrollToTop()">Top</button>
<script>
// 返回顶部按钮的显示与隐藏
window.onscroll = function() {
var button = document.getElementById("back-to-top");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
button.style.display = "block";
} else {
button.style.display = "none";
}
};
// 返回顶部动作
function scrollToTop() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
</script>
</body>
</html>
在这个示例中,我们创建了一个固定在页面右下角的返回顶部按钮。当用户向下滚动页面超过20px时,按钮会显示出来,点击按钮则会使页面滚动回顶部。通过调整样式和按钮位置,可以根据实际需求定制页面返回顶部按钮的设计。