标签:style document 顶部 top height header goTop 按钮 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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。