如何使用 Jquery 设置 DIV 的绝对位置?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6505067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to setup absolute position of a DIV with Jquery?
提问by Vonder
I have a code like that:
我有一个这样的代码:
$('#lol').css({ position: "absolute",
marginLeft: 0, marginTop: 0,
top: 0, left: 0});
The problem is that my div is positioned relatively, so it is point 0 of a div rather than the entire window. Why is that?
问题是我的div是相对定位的,所以它是一个div的0点而不是整个窗口。这是为什么?
回答by DanielB
As pointed out in the other answers, at least one of the parent element of #lol
has a position
set, that causes your element to be positioned within the parent.
正如其他答案中所指出的,至少一个 的父元素#lol
有一个position
集合,这会导致您的元素定位在父元素中。
A solution with jQuery would be to attach the element directly to body.
jQuery 的一个解决方案是将元素直接附加到正文。
$('#lol').css({
position: "absolute",
marginLeft: 0, marginTop: 0,
top: 0, left: 0
}).appendTo('body');
This will make it to appear top left of the window.
这将使它出现在窗口的左上角。
回答by Pekka
Why is that?
这是为什么?
If you want to use position: absolute
relatively to the entire window, you need to make sure that your #lol
has no parent elements also positioned absolute
, fixed
, or relative
.
如果你想用position: absolute
相对整个窗口,你需要确保你#lol
没有父元素也放置absolute
,fixed
或relative
。
Otherwise, any positioning you specify will take place relative to them.
否则,您指定的任何定位都将相对于它们进行。
回答by Wex
Elements that have position: relative
or position: absolute
will be positioned relative to the closest parent that has position: relative
or position: absolute
. So, if you want your element to be positioned relative to the entire window, keep it outside of any parent wrappers with relative or absolute positions.
具有position: relative
或position: absolute
将相对于具有position: relative
或的最近父元素定位的元素position: absolute
。因此,如果您希望元素相对于整个窗口定位,请将其置于任何具有相对或绝对位置的父包装器之外。
回答by user801985
That's just how positioning works. If you have any parent elements with any position specified the absolute positioning will happen relative to them.
这就是定位的工作原理。如果您有任何指定了任何位置的父元素,绝对定位将相对于它们发生。
If you want it to the window but can't do away with any of the other elements' positioning you'll need to remove the item from regular page flow either manually or with a bit of JS.
如果您希望将其显示在窗口中,但又无法取消任何其他元素的定位,则您需要手动或使用一些 JS 从常规页面流中删除该项目。
回答by chandanjha
If you want to use absolute:positionon an element relative to the entire window screen than any parent of that element should not given any position values like absolute,fixed or relative,because the element will take the position relative to its parent if any position attribute is given to it. Hope it answer you well...:)
如果你想在相对于整个窗口屏幕的元素上使用绝对:位置,那么该元素的任何父元素都不应该给出任何位置值,如绝对、固定或相对,因为如果有任何位置,元素将采用相对于其父元素的位置属性被赋予它。希望它能很好地回答你...:)