我说的代码:每当按下'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>
标签中,没有加载事件侦听器。我无法复制该代码段。要查看原始代码,请参阅revisions。
答案 0 :(得分:2)
首先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()'>
答案 1 :(得分:0)
问题在于范围界定。在函数checkKey()中找不到变量colorAtRandom。使其全球化,它将起作用。
第二个问题是事件侦听器无法正常工作。我改变了它,所以它将被添加到按钮被点击。由于document.write
创建了一个新文档,因此您将丢失在加载时创建的事件监听器。因此不建议这样做。
这应该解决它。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Tester</title>
<script type="text/javascript">
var colors = ['#ce0e0e', '#079b0c', '#3e3fd6']; //red, green, blue
var colorAtRandom = colors[Math.floor(Math.random() * colors.length)]; // this variable has to be global.
function changeBackground(){
//document.write("use 'a' key to change background"); using document.write is not advised.
colorAtRandom = colors[Math.floor(Math.random() * colors.length)]; // chose new random color. made it global to get rid of scope
document.body.style.backgroundColor = colorAtRandom;
document.getElementById('button').className = 'hidden';
window.addEventListener('keydown', checkKey, false); // add the event listener when button is pressed.
}
function checkKey(key){
console.log("test");
if (key.keyCode == 65){
if (colorAtRandom != '#ce0e0e'){
changeBackground();
} else {
alert('background is red');
changeBackground(); // change background after alert so it doesnt get stuck.
}
}
}
</script>
<style>
.hidden {
display:none;
}
.show {
display:block;
}
</style>
</head>
<body>
<input id=button type=button value='change backgound color' onclick='changeBackground()'>
</body>
</html>