Button click works on second click only

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

    Setting CSS style does not pervade to x.style.display so when you click the first time x.style.display actually equals "", so it hits your else block and sets the style.display to none, 2nd time and it hits the first branch of the conditional and shows your div.

    Either use computedStyle to grab the actual style, or, this would be a little easier using classes.

    JS:

    function show () { var x = document.querySelector('#myDiv') x.classList.toggle('show') }

    CSS:

    .show { display: 'block'; }

    Classlist is supported for all modern browsers but some really old ones will struggle with it, although good polyfills exist.

提交回复
热议问题