javascript - 如果语句不适用于颜色代码
问题描述
我所说的代码:只要按下“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>
,没有加载事件侦听器。我无法为片段重现它。要查看原始代码,请参阅修订版。
解决方案
首先不要使用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()'>
推荐阅读
- java - 在 mvn 测试期间显示完整的错误跟踪
- python - 有没有办法在 Flask 服务器和它创建的线程之间共享数据(不使用全局变量?)
- javascript - iFrame 相对于源内容的高度,然后保持高度动态
- amazon-dynamodb - 如何扫描 DynamoDB 表以在每个分区键中仅检索一项
- mysql - 如何将 mysql_upgrade 作为 docker compose 文件的一部分运行?
- java - 多线程事务 kafka 生产者 - 我应该在关闭前刷新吗?
- r - 在 rstudio 查看器中控制数据表输出的高度
- php - 获取所有子菜单项和容器 WordPress
- ios - 如何在两个 UIImageViews 一个 View Controller,UIImagePickerController 上显示两个图像?
- bash - 在macos下连接bash中的变量时避免空格