Button click works on second click only

前端 未结 5 2081
野的像风
野的像风 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 14:54

    The problem with your code is that x.style.display corresponds with the display property attached inline to your element. It ignores your CSS selector, which means that x.style.display === 'none' is false the first time you run your function.

    Inlining display:none would fix your problem :

    ...
    → → →

    However, that's not the recommended approach here. A better way to achieve the desired result, would be to toggle a class :

    document.getElementById('myButton').addEventListener('click', function() {
        document.getElementById("myDiv").classList.toggle('hidden');
    });
    .hidden {
      display: none;
    }
    
    

提交回复
热议问题