问题
To check the scroll values of the page I used to wrap the window
object with jQuery, but when scrolling, the target element of the scroll event results to be the document
object:
$(window).scroll(function(e) {
alert('Scrolling ' + e.target);
});
What is the right object to wrap to check the scroll values?
I know the difference between them (a window can contain multiple frames thus many documents), but for a single document context I see the scroll values coincide:
alert($(window).scrollTop() === $(document).scrollTop());
EDIT:
It also happens with native JavaScript:
window.onscroll = function(e) { alert('scrolled ' + e.target); };
The element bound is window
, but the event target is document
.
About the expression written above, comparing the scrollTop value of the window
object with the one of the document
object: the jQuery documentation explains that $(window).width()
returns the width of the viewport, while $(document).width()
returns the width of the HTML DOM element; since the viewport may be smaller than the whole HTML element width, these two values may differ.
回答1:
Leaving jQuery aside for a moment, using plain JavaScript you can check the following properties of window
for the current vertical scrolling position:
window.pageYOffset;
window.scrollY;
The second one is not cross-browser according to MDN. Still according to that, on IE<9 you must check document.body.scrollTop
, as no property of window
will give you the current scroll position. Actually, document.body.scrollTop
is what I use most frequently, as in my experience it just works cross-browser (citation and checking needed here).
jQuery takes the browser differences into consideration, and grabs the right property from the right object regardless of which selector you use for .scrollTop()
(take a look at the source code). In short, it doesn't matter if you select window
or document
with jQuery when asking for .scrollTop()
. It will look for window.pageYOffset
, and if it can't find it, it will return document.body.scrollTop
.
A note about your comment on multiple documents per window: technically, each window
object only points to a single document
, and vice-versa. When you have multiple frames, there are separate window
and document
elements for each frame. For example, if you get a reference to a single iframe, you can get its own window
and document
from it:
// first iframe in main document
var ifr = document.getElementsByTagName('iframe')[0];
var ifrWindow = ifr.contentWindow;
var ifrDocument = ifrWindow.document;
// The above is good for new and old browsers;
// ifr.contentDocument is also available on modern browsers
来源:https://stackoverflow.com/questions/14059456/wrap-the-document-or-window-object-to-check-scroll-value