js上下视差滚动简单实现代码

前言: 项目中让实现一个简单的上下视差滚动,就是当页面滑动到某一固定位置时,让上下两页面出现叠加效果,恢复时,展开恢复。

功能技术实现方式:元素定位,鼠标事件

思路1:

一开始想着设置滚动条监听事件,当到固定位置时下方元素设置relative属性(这样可保证不改变其原有样式而且可以实现元素位置的调整),于是就诞生出一下代码:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <style> body{ margin: 0; padding: 0; } .div1{ width: 100%; height: 500px; background: #FF0000; position: fixed; top: 0; left: 0; } .div2{ width: 100%; margin-top: 500px; height: 1000px; background: #22B0FC; position: relative; z-index: 2;; } </style> <body> <div>1111111</div> <div>22222222222222</div> </body> <script src="https://www.jb51.net/jquery-1.8.3.min.js"></script> <script> $(document).ready(function () { $(window).scroll(function () { var scrollTop=$(window).scrollTop(); //$(window).scrollTop()这个方法是当前滚动条滚动的距离 //$(window).height()获取当前窗体的高度 //$(document).height()获取当前文档的高度 $('.div2').css('top',-scrollTop); }); }); </script> </html>

问题:运行以上代码就会发现有一个很明显的bug,虽然大体功能已经实现了,但是因为relative的元素不管如何移动,还是会占有原本的位置。然而我们的期望是,滚动条到达让下方元素底部时就不应该滑动了,如何解决呢?

思路2:

我思考了良久,但是仍然没发现可以让元素既不占位置,又不改变自身样式,所以我大胆放弃relative,选择absolute定位,这个就需要我们自己做样式的调整,具体代码如下:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <style> body{ margin: 0; padding: 0; } .clearfix:after { content: ''; display: block; clear: both; } .div1{ width: 100%; margin: 0 auto; height: 500px; background: bisque; position: fixed; top: 0; left: 0; } .div1 div{ width: 1200px; margin: 0 auto; height: 500px; background: #FF0000; } .div2{ width: 1200px; margin: 0 auto; height: 1500px; background: #22B0FC; z-index: 20000;; margin-top: 500px; } </style> <body> <div> <div>111111111111111111111111111111111111111</div> </div> <div>22222222222222</div> </body> <script src="https://www.jb51.net/jquery-1.8.3.min.js"></script> <script> var div2Height=Number($('.div2').offsetTop); var clientHeight=Number($(document).clientHeight); var totalHeight=div2Height-clientHeight; var objOffset=$('.div2').offset().top; var objOffsetLf=$('.div2').offset().left; $(document).ready(function () { //本人习惯这样写了 $(window).scroll(function () { var scrollTop=$(window).scrollTop(); var objHeight=objOffset-scrollTop; console.log(scrollTop); if(scrollTop>=0){ $('.div2').css({'left':objOffsetLf,'top':objHeight,'position':'absolute','margin-top':'0px'}); }else{ $('.div2').css({'position':'static','margin-top':'500px'}); } }); }); </script> </html>

注意:①上半部分元素的位置需要保持不动②下半部分确保层级要高于上半部分③本代码针对的是上半部分固定,如果想让其跟着动,需要确保下半部分滚动速度要大于上半部分

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzywj.html