首页 > 解决方案 > 如果语句不适用于颜色代码

问题描述

我所说的代码:只要按下“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()'>


编辑器注意:原始代码将脚本包装在<script>内部标签中<head>,没有加载事件侦听器。我无法为片段重现它。要查看原始代码,请参阅修订版

标签: javascriptif-statementbackground-colorcolor-codes

解决方案


首先不要使用document.write, secund 使您的变量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()'>


推荐阅读