Getting the z-index of a DIV in JavaScript?

2019-01-14 23:32发布

I have a div normaldiv1 with class normaldiv. I am trying to access its z-index through the style property but it always returns 0 although it's set to 2 in the stylesheet.

CSS:

.normaldiv
{
    width:120px; 
    height:50px; 
    background-color:Green;  
    position: absolute;
    left: 25px;
    top:20px;
    display:block;
    z-index:2;
}

`

HTML:

<div id="normaldiv1" 
     class="normaldiv" 
     newtag="new" 
     tagtype="normaldiv1" 
     onmousedown="DivMouseDown(this.id);" 
     ondblclick="EditCollabobaTag(this.id,1);" 
     onclick="GetCollabobaTagMenu(this.id);" 
     onblur="RemoveCollabobaTagMenu(this.id);">

JavaScript:

alert(document.getElementById('normaldiv1').style.zIndex);

How can I find the z-index of an element using JavaScript?

2条回答
放荡不羁爱自由
2楼-- · 2019-01-14 23:49

try this

window.getZIndex = function (e) {      
  var z = window.document.defaultView.getComputedStyle(e).getPropertyValue('z-index');
  if (isNaN(z)) return window.getZIndex(e.parentNode);
  return z; 
};

usage

var myZIndex = window.getZIndex($('#myelementid')[0]);

(if parent gets to root it will return 0)

查看更多
欢心
3楼-- · 2019-01-15 00:06

Since z index is mentioned in the CSS part you won't be able to get it directly through the code that you have mentioned. You can use the following example.

function getStyle(el,styleProp)
{
    var x = document.getElementById(el);

    if (window.getComputedStyle)
    {
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); 
    }  
    else if (x.currentStyle)
    {
        var y = x.currentStyle[styleProp];
    }                     

    return y;
}

pass your element id and style attribute to get to the function.

Eg:

var zInd = getStyle ( "normaldiv1" , "zIndex" );
alert ( zInd );

For firefox you have to pass z-index instead of zIndex

var zInd = getStyle ( "normaldiv1" , "z-index" );
 alert ( zInd );

Reference

查看更多
登录 后发表回答