Div1(靜態 HTML)。append 動態創建 Div2 插入頁面。Div2 後添加,默認覆蓋 Div1。需求:Div1 在上層。為靜態 Div1 設置更高的 z-index,且確保兩者均為定位元素(position: relative/absolute/fixed)。
#Div1 {
position: relative; /* 或 absolute/fixed */
z-index: 10; /* 高層級 */
}
#Div2 {
position: relative; /* 必須定位,z-index 才生效 */
z-index: 5; /* 低層級 */
}
position 不為 static)。opacity < 1、transform、filter 等),子元素 z-index 僅在父內部比較,無法跨越父層級。// JS 動態插入 Div2 時,自動設置比 Div1 低
const div1 = document.getElementById('Div1');
const div2 = document.createElement('div');
div2.id = 'Div2';
div2.style.position = 'relative';
div2.style.zIndex = (parseInt(window.getComputedStyle(div1).zIndex) || 0) - 1;
document.body.appendChild(div2);
靜態元素 Div1 設置 position: relative; z-index: 10,動態 Div2 設置 position: relative; z-index: 5(或 JS 計算),即可確保 Div1 永遠覆蓋 Div2。