javascript移动的盒子效果代码 时间:2020-05-12 人气:0 移动的盒子 练习 <script language="JavaScript" type="text/javascript"> function $(obj){ return document.getElementById(obj); } //事件绑定通用方法 function addListener(element,e,fn){ if(element.addEventListener){ element.addEventListener(e,fn,false); } else { element.attachEvent("on" + e,fn); } } var client_width = document.body.clientWidth + document.body.scrollLeft;//页面的宽度 var client_height = document.body.clientHeight + document.body.scrollTop;//页面的高度 //一个单击事件的过程是:keydown keypress keyup var CodeList = new Array(); //在数组中先遍历移除keyCode,再把keyCode加到末尾 CodeList.Put = function(keyCode){ var retVal = CodeList.Remove(keyCode); CodeList.push(keyCode); } //移除数组中的keyCode CodeList.Remove = function(keyCode){ for(var i = 0;i < CodeList.length;i++){ if(CodeList[i] == keyCode){ CodeList.splice(i,1); } } } //获取按键,也就是数组中的最后一个元素 CodeList.getKey = function(){ //当数组中没有元素的话那么是0,为什么会是<0呢? if(CodeList.length <= 0){ return null; }else{ return CodeList[CodeList.length - 1]; } } function Box(){ } Box.prototype.KeyUp = function(evt){ var evt = window.event?window.event:evt; if(evt.keyCode >=37 && evt.keyCode <= 40){ //松开时的是方向键,把该方向键放在数组末尾,并且移除数组中的该元素 CodeList.Remove(evt.keyCode); //数组中已经没有存储按键信息 if(CodeList.getKey() == null){ window.clearInterval(timer); timer = null; } } } Box.prototype.Move = function(){ var current_x = $("box").offsetLeft;//盒子当前x坐标 var current_y = $("box").offsetTop;//盒子当前y坐标 var obj = CodeList.getKey(); if(obj == null){ return; } switch(obj) { //左 case 37: var left = current_x - 2; $("box").style.left = left + "px"; $("sbox").style.left = left - 20 + "px"; $("sbox").style.top = current_y + 15 + "px"; break; //上 case 38: var top = current_y - 2; $("box").style.top = top + "px"; $("sbox").style.top = top - 20 + "px"; $("sbox").style.left = current_x + 15 + "px"; break; //右 case 39: var left = current_x + 2; $("box").style.left = left + "px"; $("sbox").style.left = left + 50 + "px"; $("sbox").style.top = current_y + 15 + "px"; break; //下 case 40: var top = current_y + 2; $("box").style.top = top + "px"; $("sbox").style.top = top + 50 + "px"; $("sbox").style.left = current_x + 15 + "px"; break; } } Box.prototype.KeyDown = function(evt){ var evt = window.event?window.event:evt; if(evt.keyCode >=37 && evt.keyCode <= 40){ //先移除数组中相同的元素,后加到数组末尾 CodeList.Put(evt.keyCode); } if(timer == null){ timer = window.setInterval(function(){g.Move();},30); } } // www.qb5200.com 测试通过 var g = new Box(); addListener(document,"keydown",g.KeyDown); addListener(document,"keyup",g.KeyUp); var timer = null; //初始化 window.onload = function(){ $("box").style.top = "200px"; $("box").style.left = client_width/2 + "px"; $("sbox").style.top = "180px"; $("sbox").style.left = client_width/2 + 15 + "px"; } </script> [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行] 加载全部内容