绝对定位浮动元素时的奇怪行为 [英] Strange behaviour when absolutely positioning floated elements

查看:210
本文介绍了绝对定位浮动元素时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用此代码绝对定位一些浮动的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 and left for all the divs. 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 divs are floated. As you had it, each div was being removed from normal flow by being set to position: absolute, so all the subsequent divs 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/

这篇关于绝对定位浮动元素时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆