Home  >  Article  >  Web Front-end  >  The correct way to use javascript scrollTop

The correct way to use javascript scrollTop

高洛峰
高洛峰Original
2016-12-29 10:17:011769browse

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:
doctype:
window .pageYOffset: undefined
document.documentElement.scrollTop:100
document.body.scrollTop:0


##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!


##
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