用于页面上:在浏览页面时,会往下翻,而添加这个代码可以一键返回到顶部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>回到顶部</title>
<style>
* {
margin: 0;
padding: 0;
}
/* 我们给body上高度,要不然没有滚动条 */
body {
height: 2000px;
}
.box {
height: 100px;
text-align: center;
line-height: 100px;
font-size: 40px;
background-color: red;
}
.top {
width: 45px;
height: 50px;
background-color: pink;
opacity: 0;
/* 小手样式 */
cursor: pointer;
/* 我们给它设置固定定位 */
position: fixed;
right: 0;
bottom: 100px;
}
</style>
</head>
<body>
<!-- 最顶部 -->
<div class="box">我是最顶部,好观察</div>
<!-- 回到顶部的按钮 -->
<div class="top">回到顶部</div>
</body>
<script>
// 我们获取回到顶部按钮
let topBack = document.querySelector(".top")
// 我们给window设置滚动事件
window.onscroll = function () {
// 获取被卷去的部分
// document.documentElement是获取html
let n = document.documentElement.scrollTop
// 判断,使用三元运算符,如果大于300显示,小于300隐藏
topBack.style.opacity = n >= 300 ? 1 : 0
}
// 给回到顶部绑定点击事件
topBack.onclick = function(){
document.documentElement.scrollTop = 0
}
</script>
</html>
--以上皆为个人课后总结,以上有不对的地方,希望大家可以指出,感谢大家!