Home >Web Front-end >JS Tutorial >The correct way to use javascript scrollTop_Basic knowledge

The correct way to use javascript scrollTop_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:15:23992browse

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 between window.pageYOffset/document.documentElement.scrollTop/document.body.scrollTop under the browser
Example:

Copy code The code is as follows:

window.scroll(0,100)
console.log(“window.pageYOffset:” window.pageYOffset)
console.log(“document.documentElement.scrollTop: ” document.documentElement.scrollTop)
console.log(“document.body.scrollTop:” document.body.scrollTop)

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 scrollTop value
Perfectly get scrollTop value assignment abbreviation:

Copy code The code is as follows:

var scrollTop = window.pageYOffset|| document.documentElement.scrollTop || document.body.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