我想相对于页面上的其他元素放置一个 div。
这是初始 CSS:
#puzzle
{
display:inline-block;
vertical-align: top;
(position: static;)
}
#success
{
display: none;
position: absolute;
top: 235px;
left: 130px;
border: 3px solid blue;
border-radius:25px;
color: blue;
background-color: #cfd;
text-align:center;
padding:40px;
font-size:20pt;
}
当需要时,我执行以下代码:
let p = puz.getBoundingClientRect();
let s = getelem("success");
s.style.left = p.left;
s.style.top = p.top;
s.style.display = "block";
结果是:
puz.getBoundingClientRect()
DOMRect { x: 38, y: 183, ... }
document.getElementById("success").getBoundingClientRect()
DOMRect { x: 38, y: 33.833 ... }
(X 和 Y 是 Left 和 Top 的同义词)
看起来像这样:
问题是: 为什么 s.top 与 p.top 不同?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
#success 是绝对定位的,因此 DOM 中其他元素的流动不会影响其定位,而
top等属性会影响其定位,而 #puzzle 的位置为static(默认),并且不受top和类似,但适合文档流。来自https://www.w3schools.com/Css/css_positioning.asp
如果您希望 #success 位于 #puzzle 的左上角,您可以在 #puzzle 上设置
position:relative并确保它是 HTML 中 #success 的父级。