简体   繁体   English

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

[英]why won't this style.display work?

Why won't this work? 为什么这不起作用? It should check the element for display css style. 它应检查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: UPDATE2:

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

I haven't set it with css either! 我也没有用css设置它!

If the style is set via CSS or is a default style, you need to get the computed style of the element: 如果样式是通过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");

First try alerting just the style.display and see what it contains: 首先尝试仅提醒style.display并查看它包含的内容:

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). style仅引用style属性中的内容(或在style属性上通过JS设置)。 It's possible that the display is set through the class, and therefore el.style.display won't show anything. 显示是通过类设置的,因此el.style.display不会显示任何内容。

[ Update ]:Given the update, the reason no alert happens is because style.display will be "", not "inline" or "block". [ 更新 ]:鉴于更新,没有警报发生的原因是因为style.display将是“”,而不是“内联”或“阻止”。 It won't be "inline" or "block" until you set it to something, either in the style attribute or by setting .style.display . 在将它设置为某个内容之前,它不会是“内联”或“阻止”,无论是在style属性中还是通过设置.style.display

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM