如果网站中某个页面内容比较多,我们想要浏览全部内容,就需要滚动页面浏览整个页面,当用户打开页面底部内容后,如果,想要快速返回页面顶部,我们可以在页面中添加一个顶部的按钮,那么,问题来了,我们该如何编写代码实现该需求呢?
关键代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>返回顶部案例</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 2000px; /* 撑开页面,产生滚动条 */
background: #f5f5f5;
font-size: 16px;
line-height: 1.8;
padding: 30px;
}
.content {
max-width: 800px;
margin: 0 auto;
}
/* 返回顶部按钮样式 */
.back-top {
position: fixed;
right: 30px;
bottom: 50px;
width: 45px;
height: 45px;
background: #2385ff;
color: #fff;
text-align: center;
line-height: 45px;
border-radius: 50%;
cursor: pointer;
display: none; /* 默认隐藏 */
z-index: 999;
}
.back-top:hover {
background: #1976d2;
}
</style>
</head>
<body>
<div class="content">
<h3>网站测试内容</h3>
<p>往下滚动页面,就能看到右下角返回顶部按钮出现</p>
<p>多复制几行文字,把页面拉长,方便测试滚动效果</p>
<p>多复制几行文字,把页面拉长,方便测试滚动效果</p>
<p>多复制几行文字,把页面拉长,方便测试滚动效果</p>
<p>山东企业网站建设</p><p>泰安外贸网站推广</p><p>青岛网站优化</p><p>枣庄SEO</p><p>烟台网络推广</p><p>潍坊关键词排名提升</p>
</div>
<!-- 返回顶部按钮 -->
<div class="back-top">↑</div>
<script>
let backTop = document.querySelector('.back-top');
// 监听页面滚动
window.onscroll = function(){
// 滚动超过300px显示按钮
if(window.scrollY > 300){
backTop.style.display = 'block';
}else{
backTop.style.display = 'none';
}
};
// 点击平滑返回顶部
backTop.onclick = function(){
window.scrollTo({
top: 0,
behavior: 'smooth' // 平滑滚动
});
};
</script>
</body>
</html>
评论