Strange behaviour when absolutely positioning floated elements
I'm trying to absolutely position some floated divs using this code:
$(function() {
$('#wrapper div').each( function( index, item ) {
alert( $(this).position().left );
$(this).css({position:'absolute', top:$(this).position().top, left:$(this).position().left});
});
});
What I can't figure out is why when I set position:absolute $(this).position() always returns {top:0, left:0}. How can I get the proper co开发者_如何学Goordinates and set the position to absolute?
I've set up a jsfiddle to illustrate this http://jsfiddle.net/SxJCb/4/
Short answer:
Set only top
and left
for all the div
s. Once that has been done, then set position: absolute
on all of them.
See: http://jsfiddle.net/thirtydot/SxJCb/6/
$('#wrapper div').each( function( index, item ) {
$(this).css({top:$(this).position().top, left:$(this).position().left});
}).css({position:'absolute'});
Long answer: (an explanation of what's going on)
All the div
s are floated. As you had it, each div
was being removed from normal flow by being set to position: absolute
, so all the subsequent div
s shifted back a place. So, the second div
moves to where the first one was, etc.
Here's a slow motion demo of what was happening: http://jsfiddle.net/thirtydot/SxJCb/7/
var x = $("#wrapper div").offset().left;
var y = $("#wrapper div").offset().top;
this can help
You probably need to append 'px' to the end of the top and left properties when setting css values directly.
精彩评论