简体   繁体   中英

Javascript only recognizising inline style and not style set in head

I have simple JS function that toggles the DISPLAY of a DIV. The DIV display is set to 'none' by default. If I use an inline style to set the display, it works fine, but if I set the style in the head it only works after I run the function the second time. So it only sees that the display is set to none after the display is set in the function. It doesn't recognize that it is set in the CSS in the head. If I use an inline style, it works fine.

Also, if I change my conditional statement from:

if (OBJ.style.display == 'none')

to

if (OBJ.style.display = 'none')

Use window.getCurrentStyle or element.currentStyle in order to obtain style from the head or body. They're supported by different browsers so here's a cross-browser example:

function getStyle( elem, style ) {
  var a = window.getComputedStyle,
      b = elem.currentStyle;

  if ( a ) return a( elem ).getPropertyValue( style );
  else if ( b ) return b[ style ];
}

getStyle( document.getElementById('OBJ'), 'display' )

The style property of an element only contains the inline style, not inherited styles or styles from a style sheet.

You can use the offsetHeight property to check if the element has any size, as it is zero when the element is not visible.

if (OBJ.offsetHeight == 0) ...

Another suggestion is to use css classes:

css:

.hide{
 display:none;   
}

html:

<div id="mydiv" class="hide">hello world</div>
<button onclick="toggle();">toggle</button>

js:

function toggle(){
    var obj = document.getElementById('mydiv');
    if(obj.className == 'hide')
        obj.className = '';
    else
        obj.className = 'hide'
}

http://jsfiddle.net/XBhMA/1/

Note this will only work if the element contains only one class. If it contains more, you will need to modify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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