Home > Article > Web Front-end > The correct way to use javascript scrollTop
javascript scrollTop Gets the offset of the scroll bar relative to its top (such as making a "return to top" button that automatically displays and hides). In practical applications, we often encounter the following problems:
document.documentElement.scrollTop is always 0 in Chrome
document.body.scrollTop is always 0 in IE and Firefox
1, each Differences in window.pageYOffset/document.documentElement.scrollTop/document.body.scrollTop under the browser
Example:
<span style="font-size: 16px;">window.scroll(0,100)<br/>console.log(“window.pageYOffset:”+window.pageYOffset)<br/>console.log(“document.documentElement.scrollTop:”+document.documentElement.scrollTop)<br/>console.log(“document.body.scrollTop:”+document.body.scrollTop)</span>IE6/7/8:
##No doctype: window. pageYOffset: undefined
document.documentElement.scrollTop:0
document.body.scrollTop:100
Safari/Chrome:
window.pageYOffset:100
document.documentElement.scrollTop:0
document.body.scrollTop: 100
Firefox/Opera:
doctype: window.pageYOffset: 100
document .documentElement.scrollTop:100
document.body.scrollTop:0
No doctype:window.pageYOffset:100
document.documentElement.scrollTop:0
document.body.scrollTop: 100
2. Get the scrollTop valuePerfectly get the scrollTop value assignment abbreviation:
<span style="font-size: 16px;">var scrollTop = window.pageYOffset|| document.documentElement.scrollTop || document.body.scrollTop;</span>
More Please pay attention to the PHP Chinese website for articles related to the correct usage of javascript scrollTop!