单击按钮仅在第二次单击时有效 [英] Button click works on second click only
问题描述
我下面有一个按钮和一个div,该按钮必须显示此div onclick,我编写了该函数,一切都很好,但是它仅在第二次单击时有效,我不知道为什么,这是我的代码:
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 out why, here is my code:
function showDiv() {
var x = document.getElementById('myDiv');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
#myDiv{
display: none;
}
<button type="button" class="btn btn-default" onclick="showDiv()">Show div</button>
<div id="myDiv">
test
test
test
test
test
test
</div>
推荐答案
设置CSS样式并不适用于x.style.display
,因此,当您第一次单击时,x.style.display
实际上等于""
,因此会触及else块并将style.display
设置为none
,第二次,它到达条件的第一个分支并显示div.
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.
要么使用computedStyle
来获取实际样式,要么使用类会更容易一些.
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')
}
function show () {
var x = document.querySelector('#myDiv')
x.classList.toggle('show')
}
CSS:
.show {
display: 'block';
}
.show {
display: 'block';
}
Classlist
,但是尽管存在良好的polyfills,但某些确实较旧的浏览器仍会遇到困难.
Classlist
is supported for all modern browsers but some really old ones will struggle with it, although good polyfills exist.
这篇关于单击按钮仅在第二次单击时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!