代码描述:js键盘操作div位置。js键盘操作div位置源码实例
通过键盘操作页面中元素的位置,这是常见的功能,比如通过键盘的上下左右键来调整元素的位置,当然也可以是其他键,下面就通过代码实例介绍一下如何实现此功能,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="author" content="https://www.51qianduan.com/" /> <title>51前端</title> <script type="text/javascript"> window.onload=function(){ var obj=document.getElementById("thediv"); var range=1; var toLeft=toRight=toTop=toBottom=false; var move=null; document.onkeydown=function(event){ var event=event||window.event; switch(event.keyCode){ case 37:toLeft=true;break; case 38:toTop=true;break; case 39:toRight=true;break; case 40:toBottom=true;break; } move=setInterval(function(){ if(toLeft){ obj.style.left=parseInt(obj.offsetLeft-range)+"px"; } if(toRight){ obj.style.left=obj.offsetLeft+range+"px"; } if(toTop){ obj.style.top=obj.offsetTop-range+"px"; } if(toBottom){ obj.style.top=obj.offsetTop+range+"px"; } },10); }; document.onkeyup=function(event){ clearInterval(move); switch(event.keyCode){ case 37:toLeft=false;break; case 38:toTop=false;break; case 39:toRight=false;break; case 40:toBottom=false;break; } }; }; </script> </head> <body> <div style="width:50px;height:50px;background-color:green;position:absolute;" id="thediv"></div> </body> </html>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能