Button click works on second click only

前端 未结 5 2041
野的像风
野的像风 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:12

    You have set the style in css.So the value of x.style.display is not none initially.it wolud be empty.So set that style initially. or use getComputedStyle to get the CSS rule

    function showDiv() {
        var x = document.getElementById('myDiv');
     
        if (x.style.display === 'none') {
            x.style.display = 'block';
        } else {
            x.style.display = 'none';
        }
    }
    #myDiv{
      display: none;
    }
    
    
    

    if the element's display is being inherited or being specified by a CSS rule, compute the style using getComputedStyle

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

提交回复
热议问题