JQuery fixed floating Sidebar (jQuery fixed Sidebar)
This function is now widely used. If the page is relatively high, when the scroll bar is dragged to the bottom of the page, a fixed DIV box following the browser will appear on the sidebar. The idea is as follows: first, obtain the distance from the DIV to be followed to the top of the page, and then determine that when the browser's rolling distance is greater than the distance from the DIV itself to the top, add the CSS attribute fixed.
This function is now widely used. If the page is relatively high, when the scroll bar is dragged to the bottom of the page, a fixed DIV box following the browser will appear on the sidebar. The idea is as follows: first, obtain the distance from the DIV to be followed to the top of the page, and then determine that when the browser's rolling distance is greater than the distance from the DIV itself to the top, add the CSS attribute 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('inclusidebar'{.css ('margintop'). replace (/auto/, 0 )); Var footTop = $ ('# footer'). offset (). top-parsefloat('character footer'character .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 { Certificate ('inclusidebar'mirror.removeclass('fixed'mirror.css ({ Position: 'absolute ', Top: (maxY-top) + 'px' }); } } Else { $ ('# Sidebar'). removeClass ('fixed '); } }); }); |