<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript">window.onload = function () { var dv = new Keymove("dv"); } function Keymove(ID) { this.time = 50; this.distance = 5; this.top = false; this.buttom = false; this.left = false; this.right = false; this.dv = document.getElementById(ID); var _this = this; setInterval( function () { _this.keym(); }, this.time ); document.onkeydown = function (ev) { var ev = ev || event; _this.onkeydown(ev); } document.onkeyup = function () { var ev = ev || event; _this.onkeyup(ev); } } Keymove.prototype.keym = function () { if (this.left) { this.dv.style.left = this.dv.offsetLeft - this.distance + "px"; } if (this.top) { this.dv.style.top = this.dv.offsetTop - this.distance + "px"; } if (this.right) { this.dv.style.left = this.dv.offsetLeft + this.distance + "px"; } if (this.buttom) { this.dv.style.top = this.dv.offsetTop + this.distance + "px"; } } Keymove.prototype.onkeydown = function (ev) { switch (ev.keyCode) { case 37: this.left = true; break; case 38: this.top = true; break; case 39: this.right = true; break; case 40: this.buttom = true; break; } } Keymove.prototype.onkeyup = function (ev) { switch (ev.keyCode) { case 37: this.left = false; break; case 38: this.top = false; break; case 39: this.right = false; break; case 40: this.buttom = false; break; } } onkeydbdown = function (ev) { var ev = ev || event; }</script> <style type="text/css">#dv { background: red; width: 100px; height: 100px; position: absolute; }</style> </head> <body> <div id="dv"></div> </body> </html>