为什么在使用.css()方法更改z-index值后保持不变?

Why does the z-index value remain unchanged, after being changed with the .css() method?

本文关键字:z-index css 方法 为什么      更新时间:2023-09-26

根据MDN的文档,z-index的默认值为auto

当我尝试将z-index设置为1时,如下所示:

$("body").css("z-index", 1);

检索z-index属性如下:

$("body").css("z-index");

仍然返回auto

为什么会发生这种情况,我如何检索当前设置的z-index值?

默认情况下,z-Index不支持position:static元素。

只适用于position:relative/absolute/fixed元素

elementSelector
{
    position:relative;
    z-index:1;
}
参考文献:z-index - CSS-Tricks

你需要设置元素的位置,然后只有z-index才能有效地工作…

检查jsfield

<div id="hello">deepak sharma</div>
<input type="button" id="set10" value="set zindex = 10" />
<input type="button" id="set20" value="set zindex = 20" />
<input type="button" id="get" value="get" />

$(function(){
    $("#set10").click(function(){
        $("#hello").css({"z-index":"10","position":"relative"});        
    });
    $("#set20").click(function(){
        $("#hello").css({"z-index":"20","position":"relative"});
    });
    $("#get").click(function(){
        alert($("#hello").css("z-index"));
    });
});

或者你也可以在CSS中设置position:relative,那么就不需要在你的jquery代码中设置位置。

jsfiddle