代码描述:js元素 滚动指定位置 实现固定。js元素滚动指定位置实现固定效果源码下载
很多网页都有这样的效果,比如篇幅较长的网页,能够实现侧栏的某个某块固定效果,但是这个模块并不是一开始就是固定的,而是当它移动的指定位置之后才会固定,下面就通过代码实例介绍一下如何实现此效果。 代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <style type="text/css"> body{ width:900px; margin:0px auto; line-height:23px; padding:10px; } #right{ float:right; width:750px; border:solid 1px gray; padding:10px; height:1000px; } #fix{ border:solid 1px gray; width:90px; padding:10px; background-color:#eff; height:150px; } #top{ width:92px; padding:10px; height:100px; background:red; } </style> <script type="text/javascript"> window.onload=function(){ function htmlPosition(obj){ var o=obj; var t=o.offsetTop; var l=o.offsetLeft; while(o=o.offsetParent){ t += o.offsetTop; l += o.offsetLeft; } obj.data_top = t; obj.data_left = l; } function htmlScroll(){ var top=document.body.scrollTop||document.documentElement.scrollTop; if(elFix.data_top<top){ elFix.style.position='fixed'; elFix.style.top=0; elFix.style.left=elFix.data_left; } else{ elFix.style.position='static'; } } var oldHtmlWidth=document.documentElement.offsetWidth; window.onresize=function(){ var newHtmlWidth=document.documentElement.offsetWidth; if(oldHtmlWidth == newHtmlWidth){ return; } oldHtmlWidth = newHtmlWidth; elFix.style.position = 'static'; htmlPosition(elFix); htmlScroll(); } var elFix=document.getElementById('fix'); htmlPosition(elFix); window.onscroll=htmlScroll; } </script> </head> <body> <div> <div style="float:left;width:120px; "> <div id="top"></div> <div id="fix"></div> </div> <div id="right"></div> </div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能