【问题标题】:Getting the z-index of a DIV in JavaScript?在 JavaScript 中获取 DIV 的 z-index?
【发布时间】:2009-09-07 07:27:31
【问题描述】:

我有一个 div normaldiv1normaldiv。 我试图通过 style 属性访问它的 z-index,但它总是返回 0,尽管它在样式表中设置为 2。

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);

如何使用 JavaScript 找到元素的 z-index?

【问题讨论】:

  • 我真的建议使用像 jQuery 或 Prototype 这样的库来提供帮助

标签: javascript html z-index


【解决方案1】:

由于在 CSS 部分中提到了 z 索引,因此您将无法通过您提到的代码直接获取它。您可以使用以下示例。

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;
}

传递您的元素 id 和样式属性以获取函数。

例如:

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

对于 Firefox,您必须传递 z-index 而不是 zIndex

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

Reference

【讨论】:

  • +1 但“风格”具有误导性。如果它是内联声明的,你可以直接读取它,如果它是 CSS 声明的,你就不能。重要的是 CSS 部分。
  • 最好不要在标准getComputedStyle之前使用非标准currentStyle
  • IE8:说document.defaultView不存在,[element].currentStyle也不存在(对象不支持这个属性或方法)
  • 谢谢!这对于调试非常有用。
  • 如果有人对 jQuery 等价物感兴趣:$.fn.cssComputed = function (prop) { var elm = this.get(0); var style = ""; if (window.getComputedStyle) { style = document.defaultView.getComputedStyle(elm, null).getPropertyValue(prop); } else if (elm.currentStyle) { style = elm.currentStyle[prop]; } return style; }
【解决方案2】:

试试这个

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

用法

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

(如果父级进入root,它将返回0)

【讨论】:

  • 这很好用! window.document.defaultView.getComputedStyle(e).getPropertyValue('z-index');
  • 不是; window.document.defaultViewwindow 相同;在所有这些情况下,您也可以删除 window.
  • 对我不起作用,它在元素的堆叠上下文中获取元素的 z-index,但我想要在文档的堆叠上下文中的 z-index,请参阅此可能正确的实现:@987654321 @
猜你喜欢
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
  • 2015-01-10
  • 2015-07-16
  • 1970-01-01
  • 2012-11-22
相关资源
最近更新 更多