Convert absolute position to relative

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

+5
source share
5 answers

you can change this attribute with

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

For instance:
You can use jQuery .position() or .offset() methods to set “top” and “left”, css, so that your object should remain in its place, changing from relative → absolute.

I don’t think it works the other way around.

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

+5
source

Since formatting comments does not work, I will post the solution here

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

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

But when I saved the offset and set it again after changing to relative, the position will be 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 }); 
+8
source

If you really want to get the overall top offset of an element that is a child with absolute and relative positions, you can 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 basically the code for the solution given by the plunger above.

+2
source

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

The problem of moving from relative to absolute is that element.offsetTop and offsetLeft

only gives the offset of your element to its parent element. You need to measure 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 + 

and etc.)

+1
source

You can easily change it from the absolute one using the offsetLeft and offsetTop values ​​in both the left and top styles.

On the other hand, more complicated. You basically have to change it to relative and see where it ended, and then calculate the new offset values ​​from the current offset and the desired location.

Note that when 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 does not affect other elements. Thus, if you change the absolute and relative positioning, you may need to make changes to other elements if you do not want them to move.

0
source

Source: https://habr.com/ru/post/949583/


All Articles