力“位置:绝对”相对于文档而不是父容器
我试图将 div 插入正文的任何部分,并使其 position:absolute
相对于整个文档,而不是具有 position:relative
的父元素。
I am trying to insert a div into any part of the body and make its position: absolute
relative to the whole document and not a parent element which has a position: relative
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您正在寻找
position:fixed
。来自 MDN:
请注意它不起作用当...
You're looking for
position: fixed
.From MDN:
Notice it doesn't work when...
您必须将
div
放置在position:relative
元素之外并放入body
中。You will have to place the
div
outside of theposition:relative
element and intobody
.我的解决方案是使用 jQuery 将 div 移出其父级:
My solution was to use jQuery for moving the div outside its parent:
如果您不想将元素附加到
body
,则可以使用以下解决方案。我来到这个问题寻找一个无需将 div 附加到主体的解决方案,因为我有一个鼠标悬停脚本,我想在鼠标悬停在新元素和生成它的元素上时运行该脚本。只要您愿意使用 jQuery,并受到 @Liam William 的回答的启发:
此解决方案的工作原理是减去元素当前的左侧和顶部位置(相对于主体),从而将元素移动到 0, 0。无论您想要相对于主体的任何位置,都只需添加左侧和顶部偏移值即可。
If you don't want to attach the element to
body
, the following solution will work.I came to this question looking for a solution that would work without attaching the div to the body, because I had a mouseover script that I wanted to run when the mouse was over both the new element and the element that spawned it. As long as you are willing to use jQuery, and inspired by @Liam William's answer:
This solution works by subtracting the element's current left and top position (relative to the body) so as to move the element to 0, 0. Placing the element wherever you want relative to the body is then as simple as adding a left and top offset value.
简单地使用 CSS 和 HTML 是不可能实现这一点的。
使用 Javascript/jQuery,您可能会将元素
jQuery.offset()
获取到 DOM,并将其与jQuery.position()
进行比较,以计算它应该出现在页面上的位置。This isn't possible with simply CSS and HTML.
Using Javascript/jQuery you could potentially get the elements
jQuery.offset()
to the DOM and compare it thejQuery.position()
to calculate where it should appear on the page.