I'm trying to determine how many pixels down I've scrolled using window.scrollY
. But this isn't supported in IE8. What is the safe, cross-browser alternative?
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
If you have a valid reason for not just using a library to handle this kind of base functionality, don't hesitate 'not to re-invent the wheel'.
Mootools is open source, and you can just 'steal' its implementation, relevant snippets:
These 2 are the core of deciding which compatibility mode your current browser it has, and then whether to use
window.pageYOffset
ordocument.body.scrollTop
based on that or evendocument.html.scrollTop
for really ancient buggy browsers.The cross-browser compatible version for
window.scrollY
isdocument.documentElement.scrollTop
. Please see the 'Notes' section of this piece of Mozilla documentation for a full, detailed workaround in IE8 and before.As mentioned here,
pageYOffset
is another alternative to window.scrollY (note though that this is only IE9+ compatible).In regard to the link above, check Example 4 for a fully compatible way to get the scroll position (it even accounts for zoom as @adeneo mentioned!) using
document.documentElement.scrollTop
anddocument.documentElement.scrollLeft
.Here, try out the example for yourself!
If you don't have to use it a lot, just do:
Based on Niels' answer, I come up with a slightly more compact solution when just the Y coord is needed:
window.scrollY & window.scrollX works fine in all modern browers like (Chrome, FireFox & Safari) but does not work in IE so to fix the use window.pageXOffset or window.pageYOffset.
Here is a sample code I wrote to fix ie issue so that the programmatic scrolling works in all browsers including IE
Based on Mozilla, and answers above, I have a created the functions below to more easily get the coords:
According to the Mozilla documentation, as cited by lifetimes above, the The
pageXOffset
property is an alias for thescrollX
property, so is stictly speaking not necessary.Anyhoo, usage is:
Tested & works on Chrome, Firefox, Opera, Edge (8-Edge), IE (7-11), IE8 on XP