页面滚动到banner区域时,侧边“返回顶部”栏的位置变为固定;
页面滚动到 main 区域时,侧边“返回顶部”栏里的字显示出来;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.w {
width: 1000px;
margin: auto;
}
.slider-bar {
position: absolute;
left: 50%;
top: 300px;
margin-left: 500px;
width: 30px;
height: 85px;
background-color: #CCCCCC;
}
.header {
height: 150px;
background-color: #5F9EA0;
margin-bottom: 10px;
}
.banner {
height: 350px;
background-color: #6495ED;
margin-bottom: 10px;
}
.main {
height: 700px;
background-color: #999999;
}
span {
display: none;
position: absolute;
}
</style>
</head>
<body>
<div class="slider-bar">
<span class="goBack">返回顶部</span>
</div>
<div class="header w">头部区域</div>
<div class="banner w">banner区域</div>
<div class="main w">主体部分</div>
</body>
<script>
var sliderbar = document.querySelector('.slider-bar');
var banner = document.querySelector('.banner');
var main = document.querySelector('.main');
var bannerTop = banner.offsetTop;
var sliderbarTop = sliderbar.offsetTop - bannerTop;
var goBack = document.querySelector('.goBack');
var mainTop = main.offsetTop;
document.addEventListener('scroll',function() {
if(window.pageYOffset >= bannerTop){
sliderbar.style.position = 'fixed';
sliderbar.style.top = sliderbarTop + 'px';
}else {
sliderbar.style.position = 'absolute';
sliderbar.style.top = 300 + 'px';
}
if(window.pageYOffset >= mainTop){
goBack.style.display = 'block';
}else {
goBack.style.display = 'none';
}
})
</script>
</html>