JS fixed DIV scrolling effect with the scroll bar (this technology is very popular now and is available on various B2C websites)

Source: Internet
Author: User

I directly paste the Code:


<Style type = "text/css">
. County_cs {position: fixed; top: 0px; background-color: # cdcdcd; width: 100% ;}
</Style>

 

 

<Div id = "xsun"> xsun </div>

<Script type = "text/javascript">
Var FixedBox = function (el ){
This. element = el;
This. BoxY = getXY (this. element). y;
}
FixedBox. prototype = {
SetCss: function (){
Var windowST = (document. compatMode & document. compatMode! = "CSS1Compat ")? Document. body. scrollTop: document.doc umentElement. scrollTop | window. pageYOffset;
If (windowST> this. BoxY ){
// This.element.style.css Text = "position: fixed; top: 0px; background-color: # cdcdcd; width: 100% ";
$ (This. element). addClass ("county_cs ");
} Else {
$ (This. element). removeClass ("county_cs ");
// This.element.style.css Text = "";
}
}
};
// Add an event
Function addEvent (elm, evType, fn, useCapture ){
If (elm. addEventListener ){
Elm. addEventListener (evType, fn, useCapture );
Return true;
} Else if (elm. attachEvent ){
Var r = elm. attachEvent ('on' + evType, fn );
Return r;
}
Else {
Elm ['on' + evType] = fn;
}
}
// Obtain the XY coordinate of the element;
Function getXY (el ){
Return document.doc umentElement. getBoundingClientRect & (function () {// retrieve element coordinates, such as setting position relative for an element or its upper-Layer Element
Var pos = el. getBoundingClientRect ();
Return {x: pos. left + document.doc umentElement. scrollLeft, y: pos. top + document.doc umentElement. scrollTop };
}) () | (Function (){
Var _ x = 0, _ y = 0;
Do {
_ X + = el. offsetLeft;
_ Y + = el. offsetTop;
} While (el = el. offsetParent );
Return {x: _ x, y: _ y };
})();
}
// Instantiation;
Var divXsun = new FixedBox (document. getElementById ("xsun "));
AddEvent (window, "scroll", function (){
DivXsun. setCss ();
});


</Script>

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.