是否可以将DIV的定位从绝对位置改为相对位置(或从相对位置改为绝对位置)?
DIV应该保持在同一位置。
DIV应该保持在同一位置。
$(object).css({position: 'absolute',top: dy, left:dx});
// dy, dx - some coordinates
$(object).css({position: 'relative'});
无法正常工作:将元素位置更改为相对位置后位置不同。
但是当我存储偏移量并在更改为相对位置后再次设置它时,位置是相同的:
$(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 });
您可以使用以下方法更改该属性:
$(object).css({position: 'absolute'});
.position()
或.offset()
来设置"top"和"left" CSS属性,这样您的对象应该保持在其位置上,在相对位置发生变化的情况下从相对位置变为绝对位置。
我认为反过来做是行不通的。
function calcTotalOffsetTop(elm)
{
var totalOffsetTop = 0,
curr = elm;
while( curr.parent().is(':not(body)') )
{
curr = curr.parent();
totalOffsetTop += curr[0].offsetTop;
}
return totalOffsetTop;
}
这基本上是Plodder提供的解决方案的代码。
你可以使用它的 offsetLeft 和 offsetTop 值作为 left 和 top 样式,从相对定位方便地更改为绝对定位。
相反的方法较难。基本上,你需要将其更改为相对定位并查看其最终位置,然后从当前偏移量和所需位置计算新的偏移值。
请注意,当定位为相对定位时,元素是页面流的一部分,并可能影响其他元素。当定位为绝对定位时,元素位于页面流之外,不会影响其他元素。因此,如果你在绝对定位和相对定位之间切换,则如果不希望它们移动,可能还需要对其他元素进行更改。
prototype.js有element.absolutize()和element.relativize方法,它们非常好用。
从相对定位到绝对定位的问题在于,element.offsetTop和offsetLeft只提供元素相对于其父元素的偏移量。
你需要测量累积偏移量(即
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.)