案例分析
- 原先侧边栏是绝对定位
- 当页面滚动到一定位置,侧边栏改为固定定位
- 页面继续滚动,会让返回顶部显示出来。
代码:
<!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>
</head>
<style>
.slider-bar {
position: absolute;
left: 50%;
top: 300px;
margin-left: 600px;
width: 45px;
height: 130px;
background-color: rgb(137, 48, 254);
}
.header {
height: 150px;
background-color: aqua;
}
.banner {
height: 250px;
background-color: pink;
}
.main {
height: 1000px;
background-color: bisque;
}
.w {
width: 1200px;
margin: 10px auto;
}
span {
display: none;
position: absolute;
bottom: 0;
}
</style>
<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>
//1.获取元素
var sliderbar = document.querySelector('.slider-bar');
var banner = document.querySelector('.banner');
var bannerTop = banner.offsetTop;//被卷去头部的大小,一定要写到滚动的外面
var sliderbarTop = sliderbar.offsetTop - bannerTop;//当我们侧边栏固定定位之后应该变化的数值
var main = document.querySelector('.main');
var goBack = document.querySelector('.goBack');
var mainTop = main.offsetTop;
//2.页面滚动事件 scroll
document.addEventListener('scroll', function () {
//console.log(window.pageYOffset);页面被卷去的部分
//3.当我们页面被卷去的头部≥可被卷去的头部大小,侧边栏改为固定定位
if (window.pageYOffset >= bannerTop) {
sliderbar.style.position = 'fixed';
sliderbar.style.top = sliderbarTop + 'px';
} else {
sliderbar.style.position = 'absolute';
sliderbar.style.top = '300px';
}
//4.当我们页面滚到main模块,就显示返回顶部goBack
if (window.pageYOffset >= mainTop) {
goBack.style.display = 'block';
} else {
goBack.style.display = 'none';
}
})
</script>
</body>
</html>