jquery realizes the example of intelligent floating div element

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.