绝对定位浮动元素时的奇怪行为 [英] Strange behaviour when absolutely positioning floated elements
问题描述
我想使用此代码绝对定位一些浮动的div:
$(function(){
$('#wrapper div')。each(function(index,item){
alert($(this).position()。left);
$(this).css :'absolute',top:$(this).position()。top,left:$(this).position()。left});
});
我不知道为什么当我设置位置:absolute $(this).position ()总是返回{top:0,left:0}。如何获得正确的坐标并将位置设置为绝对?
我设置了一个jsfiddle来说明此 http ://jsfiddle.net/SxJCb/4/
简短答案
仅为顶部
和 code> div
s。一旦完成, 在所有这些上设置 position:absolute
。
请参阅: http://jsfiddle.net/thirtydot/SxJCb/6/
$('#wrapper div') .each(function(index,item){
$(this).css({top:$(this).position()。top,left:$(this).position()。
})。css({position:'absolute'});
长回答: (解释发生了什么)
所有
div
正如你所做的那样,通过设置为position:absolute
,每个div
正常流程中被删除,后续div
已移回一个位置。所以,第二个div
移动到第一个是
这是一个慢动作演示正在发生: http://jsfiddle.net/thirtydot/SxJCb/7/
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 coordinates 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
andleft
for all thediv
s. Once that has been done, then setposition: 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, eachdiv
was being removed from normal flow by being set toposition: absolute
, so all the subsequentdiv
s shifted back a place. So, the seconddiv
moves to where the first one was, etc.Here's a slow motion demo of what was happening: http://jsfiddle.net/thirtydot/SxJCb/7/
这篇关于绝对定位浮动元素时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!