Test the browser compatibility of scrollLeft and scrollTop

Source: Internet
Author: User

Today, when I modified the pop-up window of the original group, I found that the pop-up window in Google chrome is different from that in other browsers. one-by-one troubleshooting: The scrollTop value is not added when calculating the window position. when you view the source code, you can directly use

Document.doc umentElement. scrollTop, but the value in chrome is 0.

In the context of a document, the first line also has a dtdnote. The standard browser uses document.doc umentElement. scrollTop, but chrome doesn't even know this. chrome and safari can still read scrollTop values without Document declaration. because chrome uses document. body. scrollTop.

To solve this problem, please refer to the browser class. As a result, document.body?document.doc umentElement may obtain different values. The problem is well solved.
When obtaining the scrollTop or scrollLeft of a browser or div, I encapsulate a method:
Copy codeThe Code is as follows:
Var ueScroll = (function (){
// Obtain scrollX
Function scrollX (ele ){
Var element = ele | document. body;
Return element. scrollLeft | (document.doc umentElement & document.doc umentElement. scrollLeft );
}
// Obtain scrollY
Function scrollY (ele ){
Var element = ele | document. body;
Return element. scrollTop | (document.doc umentElement & document.doc umentElement. scrollTop );
}
Return {
Left: scrollX,
Top: scrollY
}
})()

In the DEMO, browsers obtain scrollTop. The method of calling different scrollLeft values is also convenient and simple, as long as it is the same as the method of calling a common object.

This can also be directly used in textarea or div to obtain scrollTop and scrollLeft, as long as it is passed into a dom object.

Related Article

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.