<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
a{
color: #333;
text-decoration: none;
}
body{
height: 2000px;
}
.w{
width: 1200px;
margin: 10px auto;
}
.header{
height: 150px;
background-color: lightblue;
}
.banner{
height: 300px;
margin-bottom: 10px;
background-color: skyblue;
}
.main{
height: 800px;
background-color: #1d75b3;
}
.slider-bar{
position: absolute;
left: 50%;
top: 260px;
width: 40px;
height: 100px;
margin-left: 600px;
background-color: pink;
}
.goBack{
display: none;
position: absolute;
bottom: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div class="slider-bar">
<a href="#" class="goBack">返回顶部</a>
</div>
<div class="header w">头部区域</div>
<div class="banner w">banner区域</div>
<div class="main w">主体部分</div>
<script>
var goHeader=document.querySelector('.slider-bar');
var goBack=document.querySelector('.goBack');
var banner=document.querySelector('.banner');
var main=document.querySelector('.main');
var mainTop=main.offsetTop;
var bannerTop=banner.offsetTop;
var sliderTop=goHeader.offsetTop-bannerTop;
console.log(sliderTop);
document.addEventListener('scroll',function (){
if( window.pageYOffset>=bannerTop){
goHeader.style.position='fixed';
goHeader.style.top=sliderTop+'px';
}else{
goHeader.style.position='absolute';
goHeader.style.top=260+'px';
}
if (window.pageYOffset>=mainTop){
goBack.style.display='block';
}else{
goBack.style.display='none';
}
})
</script>
</body>
</html>