<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#abc{
z-index:1;
}
</style>
<script>
function z(){
alert(document.getElementById("abc").style.zIndex);
}
</script>
</head>
<body>
<div id="abc">abc</div>
<input type="button" onclick="z();" value="zIndex">
</body>
</html>
不管有没有在样式表里设定 z-index:1
在IE里,弹出的值都是 0
在Firefox里,弹出的值都是 空。这是怎么回事呢?难道样式里的 z-index 不能影响 style.zIndex 吗?

解决方案 »

  1.   

    z-index  是要在绝对定位的时候才有效
      

  2.   

    z-index 属性适用于定位元素(position 属性值为 relative 或 absolute 或 fixed的对象),用来确定定位元素在垂直于显示屏方向(称为Z 轴)上的层叠顺序(stack order)。 参考
      

  3.   

    读取element的style属性,和读取element的css设定属性是用的不同的方法。
    参考,getComputedStyle在webkit解析器下似乎有问题,以下方法在chrome和safari下还有问题.仅支持ie/ff,浏览器兼容还真是个体力活.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <style>
    #abc{
    z-index:1;
    }
    </style>
    <script>
    function z(){
    //alert(document.getElementById("abc").style.zIndex);
    var obj  = document.getElementById("abc"),
        prop = obj.currentStyle ? 'zIndex' : 'z-index';
    alert(getCssStyle(obj,prop));
    }function getCssStyle(obj,prop)
    { var p;
    if(obj.currentStyle)
    {//ie
    p = obj.currentStyle;
    return prop ? p[prop] : p;
    }
    else if(window.getComputedStyle)
    {//firefox
    p = window.getComputedStyle(obj,null);
    return prop ? p.getPropertyValue(prop) : p;
    }
    }
    </script>
    </head>
    <body>
    <div id="abc">abc</div>
    <input type="button" onclick="z();" value="zIndex">
    </body>
    </html>
      

  4.   

    只有浮动元素(position 属性值为 relative 或 absolute 或 fixed)才可能出现重叠的现象,因此需要用z-index来决定它们的层次,也就是说z-index只有对它们才是生效的,可以是非零值。而非浮动元素,注定是平面排列,绝不可能重叠,因此对它们来讲,z-index固定为0,你再设什么值也是无效的。
      

  5.   

    IE和FF(Moliza)对W3C的DOM标准实现是不一样的
    IE DOM1还没完全实现
    Moliza相对好些DOM2
      

  6.   


    为何已经设定了 position 为 absolute 了,弹出的值依然为 0 呢?
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <style>
    #abc{
    position:absolute;
    top:100px;
    left:100px;
    z-index:2;
    }
    </style>
    <script>
    function z(){
    alert(document.getElementById("abc").style.zIndex);
    }
    </script>
    </head>
    <body>
    <div id="abc">abc</div>
    <input type="button" onclick="z();" value="zIndex">
    </body>
    </html>
      

  7.   

    一般默认的index都是0不过要在div中style="position:absolute;"
      

  8.   

    z-nindex是用来定位你层的显示,当你的值越大的时候越在上面!
      

  9.   

    先不考虑样式设置的问题LZ的问题是想通过 style.属性 读取控件相关css定义的属性,是行不通的.ie : element.currentStyle
    ff : window.getComputedStyle(element,null).getPropertyValue