为什么这个style.display不起作用?

时间:2010-02-19 18:57:48

标签: javascript html

为什么这不起作用?它应检查display css样式的元素。

if (byId("annonsera_price").style.display=='inline' || byId("annonsera_price").style.display=='block'){
alert ("Hello");
}

function byId(x){
        return document.getElementById(x);
}

UPDATE2:

<input style="width:100px;" type="text" name="annonsera_price" id="annonsera_price">

我还没有用css设置它!

2 个答案:

答案 0 :(得分:5)

如果样式是通过CSS设置的,或者是默认样式,则需要获取元素的计算样式:

var el    = document.getElementById("annonsera_price");

// currentStyle for IE, getComputedStyle for standards-compliant browsers
var style = el.currentStyle || window.getComputedStyle(el);

if (style.display == "inline" || style.display == "block")
    alert("Hello");

答案 1 :(得分:3)

首先尝试提醒style.display并查看它包含的内容:

var el = document.getElementById("annonsera_price");
alert(el.style.display);

style仅引用style属性中的内容(或在style属性上通过JS设置)。可能是通过班级设置了显示,因此el.style.display不会显示任何内容。

[更新]:鉴于更新,没有警报发生的原因是因为style.display将是“”,而不是“内联”或“阻止”。在您将其设置为style属性或设置.style.display之前,它不会是“内联”或“阻止”。