优化javascript显示样式

时间:2019-02-11 07:10:51

标签: javascript

如何优化style.display JavaScript,我不想使用“ count”变量,这只是一个w3school示例,我想知道如何在不使用“ count”变量的情况下对其进行优化?

<!DOCTYPE html>
<html>
<body>

    <h2>What Can JavaScript Do?</h2>

    <p id="demo">JavaScript can hide HTML elements.</p>

    <button type="button" onclick=show()>Click Me!</button>

</body>

<script>
count = 0
function show() {
    if (count%2==0) {
        document.getElementById('demo').style.display='none'
    } else {
        document.getElementById('demo').style.display='block'
    }
    count++;

}
</script>
</html> 

4 个答案:

答案 0 :(得分:2)

您可以使用classList.toggle

function show() {

  document.getElementById('demo').classList.toggle('hide')

}
.hide {
  display: none;
}
<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick=show()>Click Me!</button>

答案 1 :(得分:0)

您基本上是在切换div,因此可以通过以下方式实现此目的。

function toggle() {
  if (document.getElementById('demo').style.display === 'block') {
    document.getElementById('demo').style.display='none'
  } else {
    document.getElementById('demo').style.display='block'
  }
}
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can hide HTML elements.</p>

<button type="button" onclick=toggle()>Click Me!</button>

</body>

</html> 

答案 2 :(得分:0)

使用布尔值。

<script>
hide = false;
function show() {
    hide = !hide
        if (hide) {
            document.getElementById('demo').style.display = 'none'
        } else {
            document.getElementById('demo').style.display = 'block'
        }
}
</script>

答案 3 :(得分:0)

如果您不想使用额外的CSS和非侵入式Javascript:

var btn = document.getElementById('btn');
var demo = document.getElementById('demo');
demo.style.display = 'block';

btn.addEventListener('click', function() {
  demo.style.display = demo.style.display === 'block' ? 'none' : 'block';
});
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button" id="btn">Click Me!</button>