淘宝侧边栏下滑页面固定案例
在淘宝页面中,我们右侧的侧边栏在下滑过一定距离后,会变为固定样式固定在屏幕右侧位置,再下滑一定距离后侧边栏会多出一个回到顶部的盒子,在往上滑动后又恢复原样,我们如何实现这个案例呢?
案例效果如下:
下拉前:
此时侧边栏为绝对定位定在右侧,滑动滚动条会跟随移动
下拉过第一个盒子的高度后:
再往下滑动过第二个盒子顶部后就会固定在这个位置不再变化 (变为固定定位)
下拉过第二个盒子的高度后:
再往下滑动过第三个盒子的顶部后 ,侧边栏就会多出回到顶部的盒子,点击可以回到顶部
实现原理:
实现这个案例我们主要用到了 获取到页面下滑被卷上去的距离:window.pageYOffset,以及盒子到页面顶部的距离 :element.offsetTop,在我们的 window.pageYOffset 的值大于第二个盒子到页面顶部的距离时,就将侧边栏的定位由 absolute 改为 fixed,同理在window.pageYOffset 的值大于第三个盒子到页面顶部的距离时,就将其回到顶部盒子的 display 改为 block,就可以实现此案例
JS代码实现:
var topbox=document.querySelector('.innertop') var centerbox=document.querySelector('.innercenter') var bottombox=document.querySelector('.innerbottom') var box=document.querySelector('.box') var center=document.querySelector('.center') var distance1=window.centerbox.offsetTop; var distance2=window.box.offsetTop-distance1 var distance3=window.bottombox.offsetTop window.addEventListener('scroll',function(){ if(window.pageYOffset>=distance1){ box.style.position='fixed' box.style.top=distance2+'px' }else{ box.style.position='absolute' box.style.top=300 +'px' } if(window.pageYOffset>=distance3){ center.style.display='block' }else{ center.style.display='none' } })
完整代码:
Document *{ margin: 0; padding: 0; } .box{ position: absolute; right: 0px; top: 300px; width: 100px; border: 1px solid; background-color: rgb(97, 97, 97); } .top{ width: 90px;height: 150px; margin: 5px; background-color: rgb(255, 187, 79); } .center{ width: 90px;height: 70px; margin: 5px; background-color: rgb(165, 165, 165); display: none; } .bottom{ width: 90px;height: 150px; margin: 5px; background-color: rgb(202, 96, 35); } .left{ float: left; margin-right: 10px; width: 110px; height: 2200px; background-color: rgb(99, 99, 99); } .right{ box-sizing: border-box; float: left; width: 1200px; height: 2200px; background-color: rgb(98, 98, 98); padding: 10px; } .innertop{ box-sizing: border-box; width: 1180px; height: 230px; margin-bottom: 10px; background-color: rgb(155, 155, 155); } .innercenter{ box-sizing: border-box; width: 1180px; height: 530px; margin-bottom: 10px; background-color: rgb(155, 155, 155); } .innerbottom{ box-sizing: border-box; width: 1180px; height: 1330px; margin-bottom: 10px; background-color: rgb(155, 155, 155); } a{ color: azure; padding: 11px; text-align: center; line-height: 70px; text-decoration: none; } var topbox=document.querySelector('.innertop') var centerbox=document.querySelector('.innercenter') var bottombox=document.querySelector('.innerbottom') var box=document.querySelector('.box') var center=document.querySelector('.center') var distance1=window.centerbox.offsetTop; var distance2=window.box.offsetTop-distance1 var distance3=window.bottombox.offsetTop window.addEventListener('scroll',function(){ if(window.pageYOffset>=distance1){ box.style.position='fixed' box.style.top=distance2+'px' }else{ box.style.position='absolute' box.style.top=300 +'px' } if(window.pageYOffset>=distance3){ center.style.display='block' }else{ center.style.display='none' } })