简体   繁体   English

CSS / JavaScript绝对与固定位置

[英]CSS/JavaScript Absolute vs Fixed positioning

I have a problem now that I can't seem to get to the bottom of. 我现在有一个问题,似乎无法深入了解。

Let's say I have this code: 假设我有以下代码:

<div id="Father">
   <div style="position:absolute" id="Son">
   Some random content here....
   </div>
</div>

Sometimes I need the Son to be full screen so I just apply some top:0; 有时我需要让儿子全屏显示,所以我只应用top:0: left:0; 左:0; and width:100%; 宽度:100%; height:100%; 高度:100%; values to it and that's about all because he is not dependent to the Father. 重视它,这全是因为他不依赖天父。 But sometimes I want the Son to stay relative to the Father and not start from the very top of the page so I just apply some position:relative; 但是有时候我希望儿子保持相对于父的关系,而不是从页面的顶部开始,所以我只是采用一些立场: to the Father and that's it. 给父亲,就是这样。 The Son is "grounded"; 儿子被“扎根”;

My problem is that if I try to use $("#Father").css("position","fixed"); 我的问题是,如果我尝试使用$(“#Father”)。css(“ position”,“ fixed”); to get the Son out again it doesn't seem to work. 再次把儿子放出来似乎没有用。 It stays relative to the Father no matter what js instructions I give. 无论我给出什么js指令,它都相对于父亲。

PS I have refreshed the Son's display (block/none), I don't expect the change to just happen with the Son standing on the screen. PS我已经刷新了儿子的显示(阻止/无显示),我不希望更改仅发生在儿子站在屏幕上的情况下。

Hope you can help me. 希望您能够帮助我。

A child will be positioned absolutely with reference to the first ancestor with a non- static position, or to the <body> element; 绝对会以非static位置参考第一个祖先,或参考<body>元素来定位孩子。

To 'free' an element from it's ancestors' constraints, simply restore it's static position: 要从祖先的约束中“释放”元素,只需恢复其静态位置即可:

$('#father').css('position','static');

Or, as shown in the comments, you could use an empty string, or invalid value, to cause the browser to discard the rule: 或者,如注释中所示,您可以使用空字符串或无效值使浏览器放弃该规则:

$('#father').css('position','');

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

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