回到顶部:
确认需求:
- 滚动条滚动超过临界点,顶部通栏显示,否则隐藏
- 滚动条超过临界点时,回到顶部按钮显示,否则隐藏
- 点击回到顶部按钮,滚动条滚动回到顶部
源码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</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;
position: fixed;
top: -80px;
left: 0;
transition: top .5s linear;
}
.goTop{
width: 50px;
height: 50px;
background-color: pink;
font-size: 20px;
text-align: center;
line-height: 25px;
color: white;
position: fixed;
bottom: 50px;
right: 50px;
}
</style>
</head>
<body>
<div class="header">顶部通栏</div>
<div class="goTop">回到顶部</div>
</body>
<script>
var header = document.querySelector(".header");
var goTop = document.querySelector(".goTop");
window.onscroll = function () {
var height = document.documentElement.scrollTop || document.body.scrollTop;
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>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</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;
position: fixed;
top: -80px;
left: 0;
transition: top .5s linear;
}
.goTop{
width: 50px;
height: 50px;
background-color: pink;
font-size: 20px;
text-align: center;
line-height: 25px;
color: white;
position: fixed;
bottom: 50px;
right: 50px;
}
</style>
</head>
<body>
<div class="header">顶部通栏</div>
<div class="goTop">回到顶部</div>
</body>
<script>
var header = document.querySelector(".header");
var goTop = document.querySelector(".goTop");
window.onscroll = function () {
var height = document.documentElement.scrollTop || document.body.scrollTop;
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>
</html>
解析:
当滚动条超过一定距离时,顶部导航栏才会显示和回到顶部按钮才会显示。默认顶部导航栏和顶部按钮是隐藏的。挺简单的案例,要是哪里不明白的私信我。