This function is now widely used, if the page is relatively high, when the scroll bar dragged down to the bottom of the page, the sidebar will appear a fixed following the browser Div box, is the idea is this: first get the div need to follow the distance from the top of the page, and then judge, When the browser scrolls more than the distance from the top of the div itself, add the CSS property fixed.
The code is as follows
HTML code:
<div id= "header" >header</div>
<div id= "Sidebarwrap" >
<div id= "sidebar" >sidebar </div>
</div>
<div id= "main" >Main</div>
<div id= "Footer" >footer</ Div>
CSS code:
Body {
margin:10px auto;
Font-family:sans-serif;
width:500px;
}
div {
border-radius:5px;
box-shadow:1px 2px 5px Rgba (0,0,0,0.3);
border:1px solid #ccc;
padding:5px;
}
#sidebarWrap {
height:400px;
width:210px;
Float:right;
position:relative;
Box-shadow:none;
Border:none;
margin:0;
padding:0;
}
#main {
width:270px;
height:4000px;
}
#footer {
clear:both;
margin:10px 0;
}
#sidebar {
width:200px;
height:300px;
Position:absolute;
}
#header {
height:200px;
margin-bottom:10px;
}
#sidebar. Fixed {
position:fixed;
top:0;
}
#footer {height:600px;}
#footer {height:600px;}
JavaScript code:
$ (function () {var top = $ (' #sidebar '). Offset (). Top-parsefloat ($ (' #sidebar '). CSS (' Margi
NTop '). Replace (/auto/, 0));
var foottop = $ (' #footer '). Offset (). Top-parsefloat ($ (' #footer '). CSS (' margintop '). Replace (/auto/, 0));
var Maxy = foottop-$ (' #sidebar '). Outerheight (); $ (window). Scroll (function (evt) {var y = $ (this). ScrollTop (), if (Y > top) {if (Y < Maxy) {$ (' #sidebar '). addclass (
' fixed '). Removeattr (' style '); else {$ (' #sidebar '). Removeclass (' fixed '). css ({position: ' absolute ', Top: (maxy-top) + ' px '});}
else {$ (' #sidebar '). Removeclass (' fixed ');});
});