我的代码说:每当按下“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/