gpt4 book ai didi

javascript - 通过 jQuery 或 JavaScript 添加到 DOM 的元素的渲染顺序

转载 作者:行者123 更新时间:2023-11-28 15:31:47 24 4
gpt4 key购买 nike

如果我有 2 个完全相同的固定位置 div 元素,并通过 jQuery 或 JavaScript 将它们添加到 DOM,我期望哪个元素会出现在顶部?

例如:

div#a {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100px;
background-color: red;
}

div#b {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100px;
background-color: red;
}

我的问题的原因是在测试过程中,我添加的 div 首先出现在顶部。我本希望添加的第二个 div 出现在顶部。

更新:请注意,我已经了解 z-index。请引用具有完全相同(默认)z-index 的 div#adiv#b 来考虑我的问题。添加到 DOM 后哪个会出现在顶部?

我的 jQuery

$( 'body' ).append( '<div id="a"></div>' );
$( 'body' ).append( '<div id="b"></div>' );

最佳答案

您应该使用 css 样式的 z-index 属性来设置元素的堆叠顺序。z-index 较大的元素始终位于 z-index 较小的元素前面。在您的示例中:

div#a {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100px;
background-color: red;
z-index: 1;
}

div#b {
position: fixed;
top: 0;
left: 0;
width: 300px;
height: 100px;
background-color: red;
z-index: 2;
}

关于javascript - 通过 jQuery 或 JavaScript 添加到 DOM 的元素的渲染顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27031769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com