javascript - If 语句不适用于颜色代码

标签 javascript if-statement background-color color-codes

我的代码说:每当按下“a”键时,背景就会改变。这种情况并没有发生,我认为这是因为 if 语句中的颜色代码所致。

var colors = ['#ce0e0e', '#079b0c', '#3e3fd6']; //red, green, blue

function changeBackground(){
   document.write("use 'a' key to change background");
   var colorAtRandom = colors[Math.floor(Math.random() * colors.length)];
   document.body.style.backgroundColor = colorAtRandom;
   document.getElementById('button').className = 'hidden'
}

window.addEventListener('keydown', checkKey, false);

function checkKey(key){
   if (key.keyCode == 65){
      if (colorAtRandom != '#ce0e0e'){
         changeBackground();
      } else {
         alert('background is red');
      }
   }
}
.hidden {
    display:none;
}
.show {
    display:block;
}
<input id=button type=button value='change backgound color' onclick='changeBackground()'>

<小时/>

Note by the editor: The original code had the script wrapped in a <script> tag inside <head> with no load event listener. I couldn't reproduce that for the snippet. To see the original code please refer to the revisions.

最佳答案

第一don't use document.write 、第二步将变量 colorAtRandom 设为全局变量。

var colors = ['#ce0e0e', '#079b0c', '#3e3fd6']; //red, green, blue
var colorAtRandom;
    function changeBackground(){
  //    document.write("use 'a' key to change background");
      colorAtRandom = colors[Math.floor(Math.random() * colors.length)];
      document.body.style.backgroundColor = colorAtRandom;
      document.getElementById('button').className = 'hidden'
    }

    window.addEventListener('keydown', checkKey,false);
    function checkKey(key){
    console.log(key.keyCode);
      if (key.keyCode == 65){
        if (colorAtRandom != '#ce0e0e'){
          changeBackground();
        } else {
          console.log('background is red');
        }
      }
    } 
  .hidden {
    display:none;
  }
  .show {
    display:block;
  }
<input id="button" type="button" value='change backgound color' onclick='changeBackground()'>

关于javascript - If 语句不适用于颜色代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52012047/

相关文章:

javascript - 一旦文本从一个 UL 移动到另一个 UL,就禁用文本

java - 应该过滤掉换行符的 if 语句不过滤换行符。

javascript - 如何在 angularjs 的 View 中使用 ng-if 值检查 null?

php - 在 PHP 中检查两个变量是否不为空

java - 来自 javascript 的 Spring Controller 调用。使用 spring 进行注释

php - 如何解析 xml 以将其插入 mysql 数据库?

javascript - .html 文件是否可以识别 .NET scriptlet 还是必须将其转换为 aspx

javascript - 使用javascript更改元素个人样式背景颜色

android - 更改圆形按钮android的背景颜色

html - Background-rgba 不适用于简单的片段?