<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.a { width: 150px; height: 300px; background-color: yellow; }
</style>
<script>
window.onload = function(){
window.document.onkeydown = function(evt){
evt = (evt) ? evt : window.event;
switch(evt.keyCode) {
case 82: //r
document.getElementById("a").style.backgroundColor = "red";
break;
case 89: //y
document.getElementById("a").style.backgroundColor = "yellow";
break;
case 71: //g
document.getElementById("a").style.backgroundColor = "green";
break;
case 66: //b
document.getElementById("a").style.backgroundColor = "black";
break;
}
};
}
</script>
</head>
<body>
<div class="a" id="a"></div>
</body>
</html>
追问啊!谢谢!不过想问一下,后面那个小题的代码有没有...
追答啥意思?
追问就是要一个【按向左把图形变红色,按向右把图形变蓝色】这两个步骤的代码...
追答哦。稍等,修改代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.a { position:absolute; width: 150px; height: 300px; background-color: yellow; }
</style>
<script>
window.onload = function(){
window.document.onkeydown = function(evt){
evt = (evt) ? evt : window.event;
var obj = document.getElementById("a");
switch(evt.keyCode) {
case 82: //r
....
case 66: //b
obj.style.backgroundColor = "black";
break;
case 37: //left
var _left = parseInt(obj.style.left.replace("px", ""));
obj.style.left = (_left - 10) + "px";
break;
case 39: //right
var _left = parseInt(obj.style.left.replace("px", ""));
obj.style.left = (_left + 10) + "px";
break;
}
};
}
</script>
</head>
<body>
<div class="a" id="a" style="left: 10px;"></div>
</body>
</html>