AWSD 按键移动
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style>.box1 {width: 400px;height: 400px;background: yellowgreen;margin: 0 auto;position: relative;}.box2 {width: 50px;height: 50px;background: aqua;position: absolute;}</style></head><body><div class="box1"><div class="box2"> </div></div></body><script>var odiv1 = document.getElementsByClassName("box1")[0];var odiv2 = document.getElementsByClassName("box2")[0];var ax = 0; // 玩家加速方向var ay = 0;var speedx = 0; // 玩家移动速度var speedy = 0;// 四个键盘按键状态,1是按下,0是抬起var keya = 0;var keyw = 0;var keys = 0;var keyd = 0;// 游戏循环var int=self.setInterval("move()",10);function move(){var T = odiv2.offsetTop //盒子距离最顶部的距离var L = odiv2.offsetLeft // 盒子距离最左边的距离if (keya == 1 && keyd == 0) {ax -= 1;} else if (keya == 0 && keyd == 1) {ax += 1;}if (keyw == 1 && keys == 0) {ay -= 1;} else if (keyw == 0 && keys == 1) {ay += 1;}if (ax < -1) {ax = -1} else if (ax > 1) {ax = 1}if (ay < -1) {ay = -1;} else if (ay > 1) {ay = 1;}if (keya == 1 || keyd == 1) {speedx += ax;}if (keyw == 1 || keys == 1) {speedy += ay;}if(keya==0&&keyd==0){speedx=0;ax=0;}if(keyw==0&&keys==0){speedy=0;ay=0;}// 速度防止过快if (speedx > 5) {speedx = 5} else if (speedx < -5) {speedx = -5}if (speedy > 5) {speedy = 5} else if (speedy < -5) {speedy = -5}// console.log(speedx);// 位置防止出界if (T + speedy < 0) {T = 0;} else if (T + speedy > 500) {T = 500;} else {T += speedy;}if (L + speedx < 0) {L = 0;} else if (L + speedx > 500) {L = 500;} else {L += speedx;}odiv2.style.left = L + "px"odiv2.style.top = T + "px"}window.onkeydown = function(e) {// 通过监听按键按下时的操作var e = e || window.event;// 取消打印// alert(e.keyCode)console.log("按键按下:" + e.keyCode)//获取当前元素到body的距离 var T = odiv2.offsetTop //盒子距离最顶部的距离var L = odiv2.offsetLeft // 盒子距离最左边的距离if (e.keyCode == 87) { //判断当前按键是不是w按键// console.log('W')// var T = T - 5// if (T < 0) {// T = 0// }// odiv2.style.top = T + "px"// ay -=1;keyw = 1;}if (e.keyCode == 83) { //判断当前按键是不是S按键// console.log('S')// var T = T + 5// if (T > odiv1.offsetWidth - odiv2.offsetWidth) {// T = odiv1.offsetWidth - odiv2.offsetWidth// }// odiv2.style.top = T + "px"// ay += 1;keys = 1;}if (e.keyCode == 65) { //判断当前按键是不是A按键// console.log('A')// var L = L - 5// if (L < 0) {// L = 0// }// odiv2.style.left = L + "px"// ax -=1;keya = 1;}if (e.keyCode == 68) { //判断当前按键是不是D按键// console.log('D')// var L = L + 5// if (L > odiv1.offsetHeight - odiv2.offsetHeight) {// L = odiv1.offsetHeight - odiv2.offsetHeight// }// odiv2.style.left = L + "px"// ax += 1;keyd = 1;}}window.onkeyup = function(e) {var e = e || window.event;if (e.keyCode == 87) { //判断当前按键是不是w按键// console.log('W')// ay = 0;keyw=0;}if (e.keyCode == 83) { //判断当前按键是不是S按键// console.log('S')// ay = 0;keys=0;}if (e.keyCode == 65) { //判断当前按键是不是A按键// console.log('A')// ax = 0;keya=0;}if (e.keyCode == 68) { //判断当前按键是不是D按键// console.log('D')// ax = 0;keyd=0;}}</script>
</html>