键盘控制div移动创建一个Move类(其实javascript没有类)function Move(){this.init.apply(this,arguments);}主要步骤如下:一、初始化创建一个div元素为div设置style属性值指定默认宽度,高度,距顶,距左,父容器,设置步长二、键盘上下左右键控制移动主要是修改div距顶,距左的距离三、父容器限制将创建的元素添加到父元素中,并使创建的元素在父元素内移动。<!DOCTYPE html> <html> <head> <title>键盘控制div移动---www.cnblogs.com/kuikui</title> </head> <body> <script type="text/javascript"> function Move() { this.init.apply(this, arguments); } Move.prototype = { init: function (options) { this.obj = document.createElement("div"); this.obj.style.position = "absolute"; this.obj.style.zIndex = "9999"; this.obj.style.border = "1px solid red"; this.setOptions(options); this.obj.style.width = this.options.oWidth + "px"; this.obj.style.height = this.options.oHeight + "px"; this.obj.style.left = this.options.oLeft + "px"; this.obj.style.top = this.options.oTop + "px"; this.bigCont = this.options.bigCont; this.step = this.options.step; this.bigCont.appendChild(this.obj); var _this = this; document.onkeydown = function (event) { _this.moving(event); } }, setOptions: function (options) { this.options = { bigCont: document.body, oWidth: 50, oHeight: 50, oLeft: 100, oTop: 100, step: 10 }; for (var p in options) { this.options[p] = options[p]; } }, moving: function (event) { event = event || window.event; switch (event.keyCode) { case 37: this.obj.style.left = this.obj.offsetLeft - this.step + "px"; break; case 38: this.obj.style.top = this.obj.offsetTop - this.step + "px"; break; case 39: this.obj.style.left = this.obj.offsetLeft + this.step + "px"; break; case 40: this.obj.style.top = this.obj.offsetTop + this.step + "px"; break; } this.limit(); return false; }, limit: function () { var doc = [document.documentElement.clientWidth, document.documentElement.clientHeight]; this.obj.offsetLeft <= 0 && (this.obj.style.left = 0); this.obj.offsetTop <= 0 && (this.obj.style.top = 0); doc[0] - this.obj.offsetLeft - this.obj.offsetWidth <= 0 && (this.obj.style.left = doc[0] - this.obj.offsetWidth + "px"); doc[1] - this.obj.offsetTop - this.obj.offsetHeight <= 0 && (this.obj.style.top = doc[1] - this.obj.offsetHeight + "px"); } } var t = new Move(); </script> </body> </html>
运行代码