Button click works on second click only

前端 未结 5 2043
野的像风
野的像风 2021-01-07 14:26

I have a button and a div under it, the button must show this div onclick, i wrote the function and everything is fine, but it works only on second click and i can\'t figure

5条回答
  •  臣服心动
    2021-01-07 15:08

    To get the value that you apply via a stylesheet (or block) you need to use getComputedStyle(). document.getElementById('myDiv').style.display can only read inline styles.

    function showDiv() {
        var x = document.getElementById('myDiv');
        if ( window.getComputedStyle(x, null).getPropertyValue("display") === 'none') {
            x.style.display = 'block';
        } else {
            x.style.display = 'none';
        }
    }
    #myDiv{
    display: none;
    }
    
    
    
    test test test test test test

提交回复
热议问题