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

前端 未结 4 1328
醉梦人生
醉梦人生 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:32

    My solution:

    Create class .hidden

    .hidden {
       display: none !important;
    }
    

    Javascript:

    function toggleHidden(id) {
        var x = document.getElementById(id);
        x.classList.toggle('hidden');
    }
    
    0 讨论(0)
  • 2020-11-30 10:35

    The javascript display property stands for only for DOM attribute

    Mozilla JS wiki, Returns an object that represents the element's style attribute.

    W3schools, The Style object represents an individual style statement

    You could use jquery's css method to get a mixed display value like

    alert($("#foo").css("display"))
    

    It should show none even if you set it with css

    0 讨论(0)
  • 2020-11-30 10:37

    It's not working because you removed it as a style attribute on your element, and placed it in an external stylesheet. DOM will not show attribute values that do not exist in the document object (DOM is merely an XML parser that reads your HTML document verbatim).

    To find CSS values set in an external stylesheet, you have to parse document.styleSheets and find the matching selector(s).

    This is where using a library like jQuery becomes really handy, because it parses external stylesheets, and has helper methods to get the full CSS applied to an element.

    Example of how you would do this in jQuery:

    value = $("#anID").css("display");
    

    PS - Looking for an empty string won't work for you, either, because display: "" is not the same as display: "none" (and in fact, is the same as display: block, for a div, because a blank essentially means inherit)

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题