JS点击返回顶部
在许多的PC端中,我们滑动滚动条,滑倒一定程度的时候,我们会出现一个向上的小三角,点击之后我们就可以直接返回到顶部,这是如何实现的呢?
在做这个效果之前,我们要准备2个事件scroll与click
复制代码,动手尝试一下吧!
<!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>
感谢大家的阅读,如有不对的地方,可以向我指出,感谢大家!