Convert absolute position to relative

2019-02-23 10:05发布

问题:

Is it possible to change DIV position from absolute to relative (and from relative to absolute)? DIV should remain on same place.

回答1:

you can change that attribute with

$(object).css({position: 'absolute'});

For instance:
You could use jQuery's methods .position() or .offset() to set "top" and "left" css attribute aswell, that way your object should stay at it's position changing from relative -> absolute.

I don't think that works vice versa.

demo code: http://jsbin.com/uvoka



回答2:

Because formatting in comments is not work I will publish solution here

$(object).css({position: 'absolute',top: dy, left:dx});
// dy, dx - some coordinates
$(object).css({position: 'relative'});

Does not work: element position after changing to relative is different.

But when I stored offset and set it again after changing to relative, position is the same:

$(object).css({position: 'absolute',top: dy, left:dx});
var x = $(object).offset().left;
var y = $(object).offset().top;
$(object).css({position: 'relative'});
$(object).offset({ top: y, left: x }); 


回答3:

If you really want to get the total top offset of an element that is a child of elements with absolute and relative positions you could use this function

function calcTotalOffsetTop(elm)
{
var totalOffsetTop  = 0,
curr            = elm;

while( curr.parent().is(':not(body)') )
{
    curr            = curr.parent();
    totalOffsetTop  += curr[0].offsetTop;
}
return totalOffsetTop;
}

this is the basically the code for the solution given by plodder above.



回答4:

prototype.js has element.absolutize() and element.relativize which work very well.

The problem with going from relative to absolute is that element.offsetTop and offsetLeft

only give the offset of your element to its parent. You need to measure the cumualtive offset (i.e.

the offset of your element to its parent +
the offset of the parent to its parent +
the offset of its parent to its parent +

etc.)



回答5:

You can quite easily change it from relative to absolute by using it's offsetLeft and offsetTop values as left and top styles.

The other way around is harder. You would basically have to change it to relative and see where it ended up, then calculate new offset values from the current offset and the desired location.

Note that when the positioning is relative, the element is part of the page flow and may affect other elements. When the position is absolute, the element is outside the page flow and doesn't affect other elements. So, if you change between absolute and relative positioning, you may need to do changes to other elements also if you don't want them to move.