<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html body{margin: 0px;padding: 0px;}
#shape{width:100px;height: 100px;background: red;position: absolute;left: 100px;top: 100px;}
</style>
<script>
window.onload=function(){
var shape=document.getElementById('shape'),x=100,y=100;
window.onkeydown=function(event){
if(event.key=='a'){
x=x-10;
};
if(event.key=='d'){
x=x+10;
};
if(event.key=='w'){
y=y-10;
};
if(event.key=='s'){
y=y+10;
};
shape.style.left=x+'px';
shape.style.top=y+'px';
};
};
</script>
</head>
<body >
<div id="shape"> </div>
</body>
</html>
是在if下面再添加有个else if 还是其他方法?
在if里面再写个判断条件,if(x>=0){x=0},同样y也是这样,加的时候判断x>=浏览器的宽,x=浏览器的宽