本文实例讲述了JS实现盒子跟着鼠标移动及键盘方向键控制盒子移动。分享给大家供大家参考,具体如下:
1. 盒子跟着鼠标移动
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin:0; padding:0; } div{ width: 100px; height: 100px; background: red; position: absolute; } </style> </head> <body> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <script> document.onmousemove=function fn(ev) { var event=window.event||ev; var oDiv=document.getElementsByTagName("div"); for(x=0;x<oDiv.length;x++){ oDiv[x].style.transition=(x*0.5)+"s"; oDiv[x].style.left=event.clientX+"px"; oDiv[x].style.top=event.clientY+"px"; } } </script> </body> </html>
2. 键盘方向键控制盒子移动
<html> <head> <meta charset="utf-8" /> <style type="text/css"> div{ width:100px; height:100px; background: red; position:absolute; left:100px; top:100px; transition: 0.1s; } </style> <script> window.onload = function(){ var oDiv = document.getElementById("div1"); var left = false; var right = false; var top = false; var bottom = false; document.onkeydown = function(ev){ var oEvent = ev || event; var keyCode = oEvent.keyCode; switch(keyCode){ case 37: left=true; break; case 38: top=true; break; case 39: right=true; break; case 40: bottom=true; break; } }; setInterval(function(){ if(left){ oDiv.style.left = oDiv.offsetLeft-10+"px"; }else if(top){ oDiv.style.top = oDiv.offsetTop-10+"px"; }else if(right){ oDiv.style.left = oDiv.offsetLeft+10+"px"; }else if(bottom){ oDiv.style.top = oDiv.offsetTop+10+"px"; } },50); document.onkeyup = function(ev){ var oEvent = ev || event; var keyCode = oEvent.keyCode; switch(keyCode){ case 37: left=false; break; case 38: top=false; break; case 39: right=false; break; case 40: bottom=false; break; } } } </script> </head> <body> <div id="div1"></div> </body> </html>
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.zyiz.net/code/HtmlJsRun测试一下运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript页面元素操作技巧总结》、《JavaScript操作DOM技巧总结》、《JavaScript切换特效与技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。