<!doctype html> <html> <head> <meta charset="utf-8"> <style type="text/css"> #gs{width:100px;height:100px;border:1px solid #000;background-color:#aaa;top:200px;position:relative;} p{position:fixed;left:10px;top:10px;border:1px solid #f00;} </style> <script src="./jquery.js"></script> <script type="text/javascript"> $(document).ready(function(e){ var startPos=$('#gs').offset(); var step=50; var endPos={}; var move=function(direction){ switch(direction){ case 'L': var lf=startPos.left-step; $.extend(endPos,{left:lf}); break; case 'R': var lf=startPos.left+step; $.extend(endPos,{left:lf}); break; case 'T': var tp=startPos.top-step; $.extend(endPos,{top:tp}); break; case 'B': var tp=startPos.top+step; $.extend(endPos,{top:tp}); break; } $('#gs').animate(endPos,'fast',function(){startPos=$('#gs').offset();}); } $(document).keyup(function(e){ switch(String.fromCharCode(e.keyCode)){ case 'A': move('L'); break; case 'D': move('R'); break; case 'W': move('T'); break; case 'S': move('B'); break; } }); }); </script> </head> <body> <div id="gs"></div> <p>效果:按下键盘上的A、D、W、S键试试</p> </body> </html>