简体   繁体   中英

Convert absolute position to relative

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

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 }); 

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

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.

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 (ie

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM