myDiv.style.display returns blank when set in master stylesheet

前端 未结 4 1344
醉梦人生
醉梦人生 2020-11-30 10:00

Short Version: Is it standard behaviour that myDiv.style.display (Javascript) returns blank when I have set that div to display:none<

4条回答
  •  既然无缘
    2020-11-30 10:43

    If you access to a DOM Element via JS(using for example getElementById) you'll not be able to read the computed style of that element, because it is defined inside the CSS file. To avoid this, you have to use property getComputedStyle(or currentStyle for IE).

    function getStyle(id, name)
    {
        var element = document.getElementById(id);
        return element.currentStyle ? element.currentStyle[name] : window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null;
    }
    

    Usage(JSFiddle):

    var display = getStyle('myDiv', 'display');
    alert(display); //will print 'none' or 'block' or 'inline' etc
    

提交回复
热议问题