实现效果:
页面下拉到一定位置,侧边栏固定定位,
页面网上滚动,恢复绝对定位
核心思想:
当滚动条滚动到一定位置时,讲侧边栏的绝对定位改成固定定位
页面回到顶部的过程中,即在原始位置时,恢复 绝对定位
问题:
元素改为固定定位,元素会有个向下移动的瞬间,这是因为top设置了值得缘故,相当于
display: fixed; top: 400px
因此我们要改正这个top的值,这里怎么计算top的值是关键,
这个案例是滚动条 滚动到 header全部被卷上去之后,侧边栏固定定位
由上图分析可见,top的值为:
sidebar.style.position = "fixed"
sidebar.style.top = sidebar.offsetTop - banner .offsetTop + 'px'
页面上滑到上面时,恢复原本的top
sidebar.style.position = "absolute"
sidebar.style.top = sidebarTop + banner.offsetTop
完整代码:
html部分:
<div class="container">
<div class="header"></div>
<div class="banner"></div>
<div class="footer"></div>
</div>
<!-- 侧边栏 -->
<div class="sidebar">
<span>返回顶部</span>
</div>
css部分:
<style>
.container {
width: 80vw;
margin: 0 auto;
}
.header {
height: 200px;
background-color: antiquewhite;
}
.banner {
height: 300px;
background-color: rgb(204, 240, 228);
}
.footer {
height: 1000px;
background-color: rgb(216, 204, 228);
}
.sidebar {
position: absolute;
top: 400px;
right: 0px;
width: 30px;
height: 80px;
background-color: pink;
}
span {
display: none;
font-size: 12px;
color: #999;
cursor: pointer;
}
</style>
js部分:
<script>
let sidebar = document.querySelector('.sidebar')
let header = document.querySelector('.header')
let banner = document.querySelector('.banner')
let footer = document.querySelector('.footer')
let span = document.querySelector('span')
let sidebarTop = sidebar.offsetTop - banner .offsetTop
let sidebarTopOri = sidebarTop + banner.offsetTop
document.addEventListener('scroll',()=>{
if(document.documentElement.scrollTop >= banner.offsetTop) {
sidebar.style.position = "fixed"
sidebar.style.top = sidebarTop +"px"
}else {
sidebar.style.position = "absolute"
sidebar.style.top = sidebarTopOri +"px"
}
// 下拉到一定位置显示 '返回顶部'
if(document.documentElement.scrollTop >= footer.offsetTop) {
span.style.display = 'block'
}else {
span.style.display = 'none'
}
})
// 返回顶部 - 使用 scrollIntoView() 函数
span.onclick = function() {
header.scrollIntoView({
behavior:'smooth'
})
}
</script>