简体   繁体   English

强制“位置:绝对”相对于文档而不是父容器

[英]Force “position: absolute” to be relative to the document and not the parent container

我试图将div插入正文的任何​​部分并使其position: absolute相对于整个文档是position: absolute ,而不是具有position: relative的父元素。

You're looking for position: fixed . 您正在寻找position: fixed

From MDN : 从MDN

Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the viewport. 固定定位类似于绝对定位,只是元素的包含块是视口。 This is often used to create a floating element that stays in the same position even after scrolling the page. 这通常用于创建即使在滚动页面后仍保持在相同位置的浮动元素。

您将必须将div放置在position:relative元素之外并放入body

My solution was to use jQuery for moving the div outside its parent: 我的解决方案是使用jQuery将div移出其父级:

<script>
    jQuery(document).ready(function(){
        jQuery('#loadingouter').appendTo("body");
    });
</script>

<div id="loadingouter"></div>

If you don't want to attach the element to body , the following solution will work. 如果您不想将元​​素附加到body ,则以下解决方案将起作用。

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. 我遇到这个问题,是在不将div附加到主体的情况下寻求解决方案,因为我有一个鼠标悬停脚本,当鼠标悬停在新元素和生成它的元素上时,我想运行该脚本。 As long as you are willing to use jQuery, and inspired by @Liam William's answer: 只要您愿意使用jQuery,并受到@Liam William的答案的启发:

var leftOffset = <<VALUE>>;
var topOffset = <<VALUE>>;
$(element).css("left", leftOffset - element.offset().left);
$(element).css("top", topOffset - element.offset().top);

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. 此解决方案的工作原理是减去元素的当前左侧和顶部位置(相对于主体),以将元素移动到0、0。然后将元素放置在相对于主体的任意位置,就像添加左侧和顶部偏移量一样简单值。

This isn't possible with simply CSS and HTML. 仅使用CSS和HTML是不可能的。

Using Javascript/jQuery you could potentially get the elements jQuery.offset() to the DOM and compare it the jQuery.position() to calculate where it should appear on the page. 使用Javascript / jQuery,您可以将jQuery.offset()元素jQuery.offset()到DOM并将其与jQuery.position()进行比较,以计算它在页面上的显示位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM