The code is as follows, please add it to the head of the page
The code is as follows |
Copy Code |
<script type= ' text/javascript ' src= ' http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver= 1.3.2 ' ></script> |
Using JavaScript to implement
Change the element ID in the following code to the element ID that needs to implement the effect and place it anywhere on the page
The code is as follows |
Copy Code |
<script type= "Text/javascript" > $ (function () { var offset = $ ("Element ID"). offset (); var toppadding = 15; $ (window). Scroll (function () { if ($ (window). scrolltop () > Offset.top) { $ ("#元素ID"). Stop (). Animate ({ MarginTop: $ (window). scrolltop ()-Offset.top + toppadding }); } else { $ ("Element ID"). Stop (). Animate ({ margintop:0 }); }; }); }); </script> |
↑↑ This method is very good ~ recommend the use of this ~↑↑
Using jquery to implement
Different from yesterday's introduction of the use of plug-in implementation
The jquery code is as follows:
The code is as follows |
Copy Code |
$.fn.smartfloat = function () { var position = function (element) { var top = element.position (). Top, pos = element.css ("position"); $ (window). Scroll (function () { var scrolls = $ (this). ScrollTop (); if (Scrolls > top) { if (window. XMLHttpRequest) { Element.css ({ Position: "Fixed", top:0 }); } else { Element.css ({ Top:scrolls }); } }else { Element.css ({ Position: "Absolute", Top:top }); } }); }; return $ (this). each (function () { Position ($ (this)); }); }; |
The calling code is as follows:
The code is as follows |
Copy Code |
$ ("#float"). Smartfloat (); |
is purple.