admin管理员组

文章数量:1291045

Why won't this work? It should check the element for display css style.

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">

I haven't set it with css either!

Why won't this work? It should check the element for display css style.

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">

I haven't set it with css either!

Share Improve this question edited Jul 13, 2016 at 20:13 littlewolf 1811 gold badge2 silver badges19 bronze badges asked Feb 19, 2010 at 18:57 user188962user188962 3
  • Btw, what doesn't work is that the alert box isn't shown, even though the display is actually set to 'block'! – user188962 Commented Feb 19, 2010 at 19:00
  • 1 Does byId("annonsera_price").style.display returns "block"? – Laserson Commented Feb 19, 2010 at 19:01
  • no, it returns a blank alert box! – user188962 Commented Feb 19, 2010 at 19:02
Add a ment  | 

2 Answers 2

Reset to default 5

If the style is set via CSS or is a default style, you need to get the puted style of the element:

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

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

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

First try alerting just the style.display and see what it contains:

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

style only references what is in the style attribute (or set through JS on the style property). It's possible that the display is set through the class, and therefore el.style.display won't show anything.

[Update]:Given the update, the reason no alert happens is because style.display will be "", not "inline" or "block". It won't be "inline" or "block" until you set it to something, either in the style attribute or by setting .style.display.

本文标签: javascriptwhy won39t this styledisplay workStack Overflow