定位 div 困難
P粉752290033
P粉752290033 2024-04-04 12:14:58
0
1
388

我想相對於頁面上的其他元素放置一個 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 不同?

P粉752290033
P粉752290033

全部回覆(1)
P粉635509719

#success 是絕對定位的,因此DOM 中其他元素的流動不會影響其定位,而top 等屬性會影響其定位,而#puzzle 的位置為static (預設),且不受top 和類似,但適合文件流。

來自https://www.w3schools.com/Css/css_positioning.asp

如果您希望 #success 位於 #puzzle 的左上角,您可以在 #puzzle 上設定 position:relative 並確保它是 HTML 中 #success 的父級。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!