使用asdw四个键来控制一个div的上下左右移动,利用计时器实现自动控制,每移动一次div随机变色
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.box{
height: 800px;
background-color: antiquewhite;
position: relative;
}
.box_c{
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid red;
position: absolute;
transition: all 0.5s;
}
</style>
</head>
<body>
<div class="box">
<div class="box_c" id="move"></div>
</div>
<script>
/*使用asdw四个键来控制一个div的上下左右移动,每移动一次div随机变色*/
var box=document.querySelector(".box");
var dom_move=document.querySelector("#move");
// document.documentElement.οnkeyup=function(event){
// console.log(event.keyCode);//A 65 S 83 W 87 D 68
// }
var sh;
document.documentElement.οnkeyup=function(event){
if(event.keyCode==65){
//A
clearInterval(sh);
sh=setInterval(function(){
var left=dom_move.offsetLeft;
if((left-50)>=0){
dom_move.style.left=dom_move.offsetLeft-50+"px";
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
var ran_color="rgb("+r+","+g+","+b+")";
dom_move.style.backgroundColor=ran_color;
console.log("a");
}
},500);
}else if(event.keyCode==68){
//D
clearInterval(sh);
sh=setInterval(function(){
var left=dom_move.offsetLeft+50;
if((left+50)<=box.clientWidth){
dom_move.style.left=dom_move.offsetLeft+50+"px";
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
var ran_color="rgb("+r+","+g+","+b+")";
dom_move.style.backgroundColor=ran_color;
console.log("d");
}
},500);
}else if(event.keyCode==87){
//w
clearInterval(sh);
sh=setInterval(function(){
var top=dom_move.offsetTop;
if((top-50)>=0){
dom_move.style.top=dom_move.offsetTop-50+"px";
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
var ran_color="rgb("+r+","+g+","+b+")";
dom_move.style.backgroundColor=ran_color;
console.log("W");
}
},500);
}else if(event.keyCode==83){
//S
clearInterval(sh);
sh=setInterval(function(){
var top=dom_move.offsetTop+50;
if((top+50)<=box.clientHeight){
dom_move.style.top=dom_move.offsetTop+50+"px";
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
var ran_color="rgb("+r+","+g+","+b+")";
dom_move.style.backgroundColor=ran_color;
console.log("S");
}
},500);
}
}
</script>
</body>
</html>