将绝对位置转换为相对位置
是否可以将 DIV 位置从绝对位置更改为相对位置(以及从相对位置更改为绝对位置)? DIV 应保留在同一位置。
Is it possible to change DIV position from absolute to relative (and from relative to absolute)?
DIV should remain on same place.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为注释中的格式不起作用,所以我将在这里发布解决方案
不起作用:更改为相对后的元素位置不同。
但是当我存储偏移量并在更改为相对后再次设置它时,位置是相同的:
Because formatting in comments is not work I will publish solution here
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:
您可以更改该属性,
例如:
您可以使用 jQuery 的方法
.position()
或.offset()
来设置“top”和“left”css 属性也是如此,这样你的对象应该保持在它的位置变化
来自亲戚->绝对。
我不认为反之亦然。
演示代码: http://jsbin.com/uvoka
you can change that attribute with
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
如果您确实想获取作为具有绝对和相对位置的元素的子元素的元素的总顶部偏移量,您可以使用此函数,
这基本上是上面 plodder 给出的解决方案的代码。
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
this is the basically the code for the solution given by plodder above.
您可以通过使用其 offsetLeft 和 offsetTop 值作为 left 和 top 样式,轻松地将其从相对更改为绝对。
反之则更难。您基本上必须将其更改为相对值并查看它结束的位置,然后根据当前偏移和所需位置计算新的偏移值。
请注意,当定位是相对的时,该元素是页面流的一部分,并且可能会影响其他元素。当位置为绝对位置时,该元素位于页面流之外,不会影响其他元素。因此,如果您在绝对定位和相对定位之间进行更改,并且不希望其他元素移动,则可能需要对其他元素进行更改。
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.
prototype.js 有 element.absolutize() 和 element.relativize ,它们工作得很好。
从相对到绝对的问题是
element.offsetTop 和 offsetLeft
仅给出元素相对于其父元素的偏移量。
您需要测量累积偏移量(即
等)
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.
etc.)