getting the position of a floated element
I have some code like this:
<style>
.box {
width: 100px;
height: 100px;
margin: 10px;
background: green;
border: 1px solid black;
float: left;
}
#wrapper {
position: relative;
}
</style>
<div id="wrapper">
<div class="box">1</div>
<div class="box">2</div>开发者_运维问答
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
<div class="box">6</div>
</div>
I need to get the left,top of each of the boxes relative to #wrapper. I'm trying to do this through jQuery.position() however, I am not getting the right results. Keep getting 0,0. Can anybody else. I think the problem here is floats... if these were absolutely positioned, I would be reading them correctly.
Here some jQuery code which will alert the left position. This works with floating well.
$(function() {
$('#wrapper div').each( function( index, item ) {
alert( $(this).position().left);
});
});
here a jsFiddle: http://jsfiddle.net/ytGYS/
Position actually works fine, just make sure you clearfix your #wrapper so that it has a height and width. The problem you're having is that with all of the elements floated, your parent #wrapper gets collapsed and has no dimensions, so jQuery can't figure out how far one thing is from the other.
Here's a fiddle with your mark-up and a code example: http://jsfiddle.net/tBwwr/
+1 for andrewheins answer:
You are totally right; if the #wrapper is too small to display all the floated elements next to each other, the $().offset() will give you the position of the elements one under each other.
The annoying thing is when the $().offset() is checked before the #wrapper gets is correct width. For example if there are two $(document).ready() functions which are executed in the wrong order. (first get offset(), then set width)
Note: I have not enough reputation to vote his answer up or leave a comment.
精彩评论