When I alert the value .position().left
, it returns 0 on Chrome. With other browsers it returns the actual number. Why does this happen?
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
For me it worked by placing the javascript code in a document ready just before the closing of the body tag
That way it executes the code after it has loaded everything
Webkit based browsers (like Chrome and Safari) can access images
width
andheight
properties only after images have been fully loaded. Other browsers can access this information as soon as just the DOM is loaded (they don't need to load the images entirely to know their size).So, if you have images in your page, with Webkit based browsers you should access
offset
information after the$(window).load
event fires, and not after the$(document).ready
event.By reading comments from http://api.jquery.com/position/, there are several ways to fix this. The one I found working is
I had the same problem..
I fixed it using:
.offset().left
instead. But be aware that are not the same: http://api.jquery.com/offset/.position().left
worked in Chrome in some tests I did, using a similar approach than David (the value was available since the first try).In my "real" application failed even reading the position on click event (which may eliminate any loading speed problem). Some comments (in other forum) say it may be related to the use of
display:inline-block
. However I couldn't reproduce the problem usinginline-block
. So it may be other thing.Webkit can be too fast sometimes, but it's often taken care of in jQuery. You can debug using something like:
This will check if and when the position is available. If you are logging "0" in infinity, the
position().left
is "never" available and you need to debug elsewhere.I use this function to correct it.