Home  >  Article  >  Web Front-end  >  About scrollLeft, scrollTop browser compatibility test_javascript skills

About scrollLeft, scrollTop browser compatibility test_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:40:031382browse

Today when I modified the original group pop-up window, I found that the position of the pop-up window under Google Chrome is different from that under other browsers. After checking one by one, it must be that the scrollTop value was missing when calculating the window position. .When looking at the source code, I found that

document.documentElement.scrollTop is used directly, but under chrome this value is 0.

When there is a document declaration, it is the first There is a dtd declaration in the line. Standard browsers recognize document.documentElement.scrollTop, but chrome does not recognize this. In the absence of a document declaration, chrome and safari can still read the scrollTop value. Because chrome passes document.body .scrollTop obtains the value.

Solve this problem: You don’t have to go to so much trouble to determine the browser category, because under different circumstances, document.body and document.documentElement may obtain different values. The problem is easily solved.
When getting the scrollTop or scrollLeft of the browser or a certain div, I encapsulated a method:

Copy code The code is as follows:

var ueScroll=(function(){
//Get scrollX
function scrollX(ele){
var element=ele || document .body;
return element.scrollLeft || (document.documentElement && document.documentElement.scrollLeft);
}
//Get scrollY
function scrollY(ele){
var element= ele || document.body;
return element.scrollTop || (document.documentElement && document.documentElement.scrollTop);
}
return {
left:scrollX,
top:scrollY
}
})()

In the DEMO, each browser obtains the scrollTop and scrollLeft values ​​in a very convenient and simple way. .

This can also be used directly in textarea or div to obtain scrollTop and scrollLeft, as long as a dom object is passed in later.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn