随机显示HTML DIV

时间:2018-10-09 19:59:20

标签: javascript html5

这可能真的很简单,但是我无法使此代码正常工作。我想做的是隐藏3个DIV,除非JavaScript代码随机选择了3个。我看了这篇文章,但仍然不明白。

<html onload="load()">   
<body>
<div class="light-grey">

<div id="q1">
div 1
</div>
<div id="q2">
div 2
</div>
<div id="q3">
div 3
</div>

</div>
</body>
<script>

function load(){
randomNumber = Math.floor(Math.random() * 3) + 1   //numbers 1 - 3
     if (randomNumber == 1) {
          document.getElementById("q1").style.display = "inline";
          document.getElementById("q2").style.display = "none";
          document.getElementById("q3").style.display = "none";
     }
     if (randomNumber == 2) {
          document.getElementById("q1").style.display = "none";
          document.getElementById("q2").style.display = "inline";
          document.getElementById("q3").style.display = "none";
     }
     if (randomNumber == 3) {
          document.getElementById("q1").style.display = "none";
          document.getElementById("q2").style.display = "none";
          document.getElementById("q3").style.display = "inline";
     }

}
</script>
</html>

我每次尝试都同时显示所有3个DIV。由于我是JavaScript新手,所以这可能真的很明显。如果您有任何疑问,请在下面评论。预先感谢。

1 个答案:

答案 0 :(得分:0)

onload属性的标签错误,这是正文而不是html所需的     

<body onload="load()">
  <div class="light-grey">

    <div id="q1">
      div 1
    </div>
    <div id="q2">
      div 2
    </div>
    <div id="q3">
      div 3
    </div>

  </div>
</body>
<script>
  function load() {
    randomNumber = Math.floor(Math.random() * 3) + 1 //numbers 1 - 3
    console.log(randomNumber);
    if (randomNumber == 1) {
      document.getElementById("q1").style.display = "inline";
      document.getElementById("q2").style.display = "none";
      document.getElementById("q3").style.display = "none";
    }
    if (randomNumber == 2) {
      document.getElementById("q1").style.display = "none";
      document.getElementById("q2").style.display = "inline";
      document.getElementById("q3").style.display = "none";
    }
    if (randomNumber == 3) {
      document.getElementById("q1").style.display = "none";
      document.getElementById("q2").style.display = "none";
      document.getElementById("q3").style.display = "inline";
    }

  }
</script>

</html>