在jQuery中如何设置“top,left”元素的属性与位置值相对于父而不是文档? [英] In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?
问题描述
.offset([coordinates])
方法设置元素的坐标,但只相对于文档。然后如何设置一个元素的坐标,但相对于父?
我找到 .position()
我尝试使用
$(#mydiv)。css({top:200,left:200});
但不起作用。
要设置相对于父级的位置,您需要设置父级的位置:relative
和 position:absolute
$(#mydiv)。css({top:200,left:200,position:'absolute'});
这是因为 position:absolute;
相对于最接近的定位的父级(即,除了默认 static
之外的任何位置属性的最接近父级)。
.offset([coordinates])
method set the coordinates of an element but only relative to the document. Then how can I set coordinates of an element but relative to the parent?
I found that .position()
method get only "top,left" values relative to the parent, but it doesn't set any values.
I tried with
$("#mydiv").css({top: 200, left: 200});
but does not work.
To set the position relative to the parent you need to set the position:relative
of parent and position:absolute
of the element
$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});
This works because position: absolute;
positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static
).
这篇关于在jQuery中如何设置“top,left”元素的属性与位置值相对于父而不是文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!