【JS】使用JS实现回到顶部按钮功能
作者:互联网
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>回到顶部</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
height: 3000px;
}
.header{
width: 100%;
height: 80px;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
color: white;
background-color: skyblue;
transition: top .5s linear;
position: fixed;
top:-80px;
left: 0;
}
.goTop{
width: 50px;
height: 50px;
background-color: #fc4a62;
font-size: 20px;
text-align: center;
line-height: 25px;
color: white;
position: fixed;
bottom: 50px;
right: 50px;
display: none;
}
</style>
</head>
<body>
<!--
需求:
1.滚动条滚动超过临界点,顶部通栏显示,否则隐藏
2.滚动条滚动超过临界点,回到顶部按钮显示,否则隐藏
3.点击回到顶部按钮,滚动条滚动回到顶部
-->
<div class="header">顶部通栏</div>
<div class="goTop">回到顶部</div>
<script>
// 1.获取元素
var header=document.querySelector('.header');
var goTop=document.querySelector('.goTop');
//2.绑定滚动事件
window.onscroll=function () {
// 2.1 获取浏览器卷去的高度
var height=document.documentElement.scrollTop||document.body.scrollTop;
// 2.2 判断卷去的高度
if (height>=300){
//显示
header.style.top='0px';
goTop.style.display='block';
}else {
//隐藏
header.style.top='-80px';
goTop.style.display='none';
}
}
//给按钮绑定事件
goTop.onclick=function () {
window.scrollTo({
top:0,
behavior:"smooth"
})
}
</script>
</body>
</html>
标签:style,document,顶部,top,height,header,goTop,按钮,JS 来源: https://www.cnblogs.com/HGNET/p/16469606.html