JavaScript基础学习 仿淘宝固定侧边栏
<!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>
.slider-bar {
position: absolute;
left: 50%;
top: 300px;
margin-left: 600px;
width: 45px;
height: 130px;
background-color: pink;
}
.w {
width: 1200px;
margin: 10px auto;
}
.header {
height: 150px;
background-color: purple;
}
.banner {
height: 250px;
background-color: skyblue;
}
.main {
height: 1000px;
background-color: yellowgreen;
}
span {
display: none;
position: absolute;
bottom: 0;
}
</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>
<script>
var banner=document.querySelector('.banner');
var sliderbar=document.querySelector('.slider-bar');
var main =document.querySelector('.main');
var goBack=document.querySelector('.goBack');
// 获取banner距离页面上边的距离
var bannerTop=banner.offsetTop;
// 获取 侧边栏距离页面上边的距离 减去 banner距离上边的距离的差来固定侧边栏
var sliderbarTop=sliderbar.offsetTop-bannerTop;
console.log('sssssss'+sliderbar.offsetTop);
// 获取 主体main距离页面上边的距离
var mainTop=main.offsetTop;
document.addEventListener('scroll',function(){
console.log(window.pageYOffset);
// 当页面卷去头部的距离大于banner距离页面上边的距离时,让侧边栏固定
if(window.pageYOffset>=bannerTop){
sliderbar.style.position='fixed';
sliderbar.style.top=sliderbarTop+'px';
}else{
sliderbar.style.position='absolute';
sliderbar.style.top='300px';
}
if(window.pageYOffset>=mainTop){
goBack.style.display='block';
}else{
goBack.style.display='none';
}
})
</script>
</body>
</html>