Javascript scrollTop forward solution use method

  • 2020-03-29 23:47:26
  • OfStack

Javascript scrollTop gets the offset of the scroll bar relative to its top (for example, making a button that automatically shows hidden "back to top"). The following problems are often encountered in practical applications:
Document. The documentElement. ScrollTop total of 0 in the Chrome
Document.body.scrolltop is always 0 in IE and firefox

1, each browser window. PageYOffset/document. The documentElement. The scrollTop/document. The body. The scrollTop difference
Example:


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)

6/7/8:
Doctype:
Window. PageYOffset: undefined
Document. The documentElement. ScrollTop: 100
Document. The body. The scrollTop: 0

No doctype:
Window. PageYOffset: undefined
Document. The documentElement. ScrollTop: 0
Document. The body. The scrollTop: 100
Safari/Chrome:
Window. PageYOffset: 100
Document. The documentElement. ScrollTop: 0
Document. The body. The scrollTop: 100

Firefox/Opera:

Doctype:
Window. PageYOffset: 100
Document. The documentElement. ScrollTop: 100
Document. The body. The scrollTop: 0

No doctype:
Window. PageYOffset: 100
Document. The documentElement. ScrollTop: 0
Document. The body. The scrollTop: 100

2. Get the scrollTop value
Perfect scrollTop assignment shorthand:


var scrollTop = window.pageYOffset|| document.documentElement.scrollTop || document.body.scrollTop;


Related articles: