What is the best cross-browser way to detect the scrollTop of the browser window? I prefer not to use any pre-built code libraries because this is a very simple script, and I don't need all of that deadweight.
相关问题
- 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
- Can php detect if javascript is on or not?
to save you all the trouble use a framework such as jquery or mootools that calculates all these values in one line (cross browser) in mootools its $('element').getTop(); in jquery you will need a plugin named dimensions if i remember correctly although most of the time even without a framework you can actually use element.getScrollTop(); to get what you'll need the only problem is on IE7 and below this calculation is somewhat buggy as it doesn not take the position value of the element into consideration for example if you got a position: absolute css attribute for that element the calculation is performed on the parent element of that element
Or just simple as:
I know its been quite a while since this thread was updated, but this is a function I created that allows developers to find the root element that actually hosts has a working "scrollTop" property. Tested on Chrome 42 and Firefox 37 for Mac OS X (10.9.5):
I hope you find this useful! Cheers.
YUI 2.8.1 code does this:
I think jQuery 1.4.2 code (a bit translated for humans) and supposing I understood it properly does this:
Unfortunatley extracting the value of
jQuery.support.boxModel
is almost impossible because you would have to add a temporary child element into document and do the same tests jQuery does.If you don't want to include a whole JavaScript library, you can often extract the bits you want from one.
For example, this is essentially how jQuery implements a cross-browser scroll(Top|Left):
Note: you'll notice that the above code contains a
browserSupportsBoxModel
variable which is undefined. jQuery defines this by temporarily adding a div to the page and then measuring some attributes in order to determine whether the browser correctly implements the box model. As you can imagine this flag checks for IE. Specifically, it checks for IE 6 or 7 in quirks mode. Since the detection is rather complex, I've left it as an exercise for you ;-), assuming you have already used browser feature detection elsewhere in your code.Edit: If you haven't guessed already, I strongly suggest you use a library for these sorts of things. The overhead is a small price to pay for robust and future-proof code and anyone would be much more productive with a cross-browser framework to build upon. (As opposed to spending countless hours banging your head against IE).