我有一个
元素,其位置受到包含它的
元素相对定位的影响。尽管删除父元素的相对定位可以解决此问题,但我们不想将其作为解决方案实施,因为这可能会破坏其他内容。是否有一种方法可以强制子元素忽略其父元素的定位?
我有一个
很遗憾,无法使用CSS动态使元素"补偿"其父元素的相对定位。除非重新设计布局并且position:fixed
不是你需要的,否则你的选择有:
position:relative
和与父元素完全相反的偏移量(你需要再次输入准确的值)。最小的麻烦是,现在你必须记住手动同步两对偏移量(父元素和子元素)。放置一个注释说“如果你更改了这个,你也必须更改#THAT”会有所帮助。总之,我建议选择#1而不是#2,只有当最佳解决方案(改变布局)对您不可用时才使用其他解决方案。
var div = document.getElementById("banner");
var parentDiv = document.getElementById("banner");
var posT = 0;
var posL = 0;
while(parentDiv = parentDiv.offsetParent){
posT += parentDiv.offsetTop;
posL += parentDiv.offsetLeft;
}
posT -= div.offsetTop;
posL -= div.offsetLeft;
div.style.top = (-1)*posT+"px";
div.style.left = (-1)*posL+"px";
.corpo{
position:relative;
margin-left:100px;
margin_top:100px;
background-color:yellow;
border:#ccc 1px solid;
padding:10px;
}
#banner{
position:absolute;
top:250px; /* inicial value - goal position considering the document reference */
left:150px; /* inicial value - goal position considering the document reference */
width:50px;
height:50px;
background-color:blue;
font-size:9px;
color:white;
font-family:Arial;
}
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
asjdghasd<br>
<div class="corpo">
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx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xxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx<br>
</div>
position:fixed
可以实现,但这可能不是你想要的。 - Jondiv
受到父级div
的影响,为什么不将其单独放在代码外面和下面?编辑:您是否有代码示例和您尝试过的更改? - Biotox*= -1
? - josh