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

The correct way to use javascript scrollTop

高洛峰
Release: 2016-12-29 10:17:01
Original
1819 people have browsed it

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>
Copy after login
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>
Copy after login

More Please pay attention to the PHP Chinese website for articles related to the correct usage of javascript scrollTop!


##
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template