JS固定边栏滚动

mac2022-06-30  83

JS固定边栏滚动

实现关键点

1、 CSS position fixed:作用把边栏做一个固定

  还要在设置一下位置,因为脱离文档流之后,会向左侧浮动,所以要设置相对浏览器右侧的距离。

2、监听window上的滚动事件

3、设置fixed条件判断的依据:滚动高度 + 屏幕高度 > 边栏高度

 

使用jquery实现

1 <script src="https://code.jquery.com/jquery.js"></script><!--引入这种格式的js文件是引入的外部的js文件,就是绝对引用。只是存储的位置是互联网--> 2 3 <script> 4 5   var jWindow = $(window);//获取window窗体 6 7   jWindow.scroll(functoin) {//实现业务逻辑操作 8 9     var scrollHeight = jWindow.scrollTop(); 10 11     var screeHeight = jWindow.height(); 12 13     var sideHeight = $('#J_BdSide').Height(); 14 15     if(scrollHeight + screeHeight > sideHeight) { 16 17       $('#J_BdSide').css({ 18 19         'position':'fixed', 20 21         'top':-(sideHeight-screenHeight),//top取负值 22 23         'right':0 24 25       }); 26 27     }else { 28 29         $('#J_BdSide').css({ 30 31           'position':'static' 32 33         }); 34 35       } 36 37   }); 38 39   window.onload(function() {//刷新页面不变 40 41     jWindow.trigger('scroll');//使用trigger触发scroll事件 42 43   });//监听window的onload事件 44 45   jWindow.resize(function(){//改变窗口大小不变 46 47     jWindow.trigger('scroll'); 48 49   });//监听resize事件 50 51 </script>

 

另一种方法js

1 <script> 2 3   var $ = function(id) { 4 5     return document.getElementById(id); 6 7   } 8 9   var addEvent = function(obj,event,fn) {//元素对象名字,绑定事件,触发的回调函数 10 11    if(obj.addEventListener) { 12 13      obj.addEventListener(event,fn,false); 14 15    }else if(obj.attachEvent) { 16 17       obj.attachEvent('on'+event,fn); 18 19    } 20 21   }//事件绑定元素 22 23   var domSide = $('J_BdSide'); 24 25   var scrollEvent = function() { 26 27     var sideHeight = domSider.offsetHeight;//获取边栏高度 28 29     var screeHeight = document.documentElement.clientHeight || document.body.clientHeight;//获取可见屏幕高度 30 31     var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop;//屏幕滚动高度 32 33     if(scrollHeight + screeHeight > sideHeight) { 34 35       domSider.style.cssText = 'position:fixed;right:0px;top:'+(-(sideHeight-screenHeigh))+'px' ';<!--/*dom操作必须加上px和top取反*/--> 36 37     }else { 38 39       domSider.style.position='static', 40 41     } 42 43   }//scroll事件做一次封装 44 45   addEvent(window,'scroll',function(){ 46 47     scrollEvent(); 48 49   }); 50 51   addEvent(window,'resize'function(){<!--把scroll事件做一次封装--> 52 53     scrollEvent(); 54 55   }); 56 57    58 59 </script>

 HTML DOM addEventListener() 方法

测试能不能调用函数

 

转载于:https://www.cnblogs.com/CiMing/p/8365535.html

相关资源:博客侧边栏模块跟随滚动条滑动固定效果的实现方法(js jquery等)
最新回复(0)