簡體   English   中英

如何在此代碼中看到 console.log?

[英]How do I see the console.log in this code?

 var hexBeat; function clarity() { setInterval(function() { function randomNumber(min, max) { return Math.random() * (max - min) + min; hexBeat = randomNumber(1, 25); console.log(hexBeat); } }, 1000) } while (hexBeat <= 20) { document.querySelector("#nachoCheddar01").style.backgroundColor = "green"; document.querySelector("#nachoCheddar01").style.left = "200px"; }
 <html> <body> <button onClick="clarity()" style="z-index:1">click for random number in console</button> <div id="nachoCheddar01" style="z-index: -1; box-sizing:border-box;border:3px solid green;background-color: blue;position:absolute;top:1%;height:100px;width:200px;">NachoCheddar01</div> <div id="nachoCheddar02" style="">NachoCheddar02</div> <div id="nachoCheddar03" style="">NachoCheddar03</div> <div id="nachoCheddar04" style="">NachoCheddar04</div> </body> </html>

我正在嘗試記錄 hexBeat,然后基於此,每當有一個小於或等於 20 的隨機數時,我想將矩形移動到屏幕右側,並更改其顏色。 但是現在我無法獲得 console.log(hexBeat) 我嘗試在任何 function 之外聲明變量。 我正在嘗試在另一個 function 中使用該變量 hexBeat,並且我已經成功地聲明了我的變量。 雖然,我正在使用間隔,但我不確定是否有更好的方法可以在每次隨機數小於或等於 20 時移動矩形。

您可以像這樣更新您的代碼:

HTML:

<html>

<body>

  <button onClick="clarity()" style="z-index:1">click for random number in console</button>
  <div class="wrapper">
    <div id="nachoCheddar01" style="z-index: -1; box-sizing:border-box;border:3px solid green;background-color: blue;position:absolute;top:1%;height:100px;width:200px;">NachoCheddar01</div>
    <div id="nachoCheddar02" style="">NachoCheddar02</div>
    <div id="nachoCheddar03" style="">NachoCheddar03</div>
    <div id="nachoCheddar04" style="">NachoCheddar04</div>
  </div>

</body>

</html>

CSS:

.wrapper {
  position: relative;
}

#nachoCheddar01 {
  position: absolute;
}

JAVASCRIPT:

var hexBeat;

function clarity() {
  setInterval(function() {
    function randomNumber(min, max) {
      return Math.random() * (max - min) + min;
    }
    hexBeat = randomNumber(1, 25);
    if (hexBeat <= 20) {
      console.log(hexBeat);
      document.querySelector("#nachoCheddar01").style.backgroundColor = "green";
      document.querySelector("#nachoCheddar01").style.left = `${document.querySelector("#nachoCheddar01").offsetLeft + 200}px`;
    }
    
  }, 1000)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM