JS实现元素上下左右移动效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS实现元素上下左右移动效果

spfLinux   2020-05-16 我要评论

本文实例为大家分享了JS实现元素上下左右移动的具体代码,供大家参考,具体内容如下

<!DOCTYPE html> 
<html lang="en"> 
<head> 
 <meta charset="UTF-8"> 
 <title>Document</title> 
 <style> 
  a { 
   cursor: pointer; 
  } 
  #cell { 
   width: 30px; 
   height: 30px; 
   background: red; 
   position: relative; 
   left: 0; 
   top: 0; 
  } 
 </style> 
</head> 
<body onload="move()"> 
 <p>友情提示:请按键盘上的上下左右键</p> 
 <div id="cell"></div> 
 <script> 
 
  function move() { 
   var a = document.getElementById("cell"); 
   a.style.left = 0; 
   a.style.top = 0; 
   document.onkeydown = function(e) { 
    var e = window.event ? window.event : e; 
    if(e.keyCode == 38) { //up 
     a.style.top = parseInt(a.style.top) - 50 + 'px'; 
     //注意要用parseInt 因为a.style.top类型是字符串 
    } 
    if(e.keyCode == 40) { /https://img.qb5200.com/download-x/down 
     a.style.top = parseInt(a.style.top) + 50 + 'px'; 
    } 
    if(e.keyCode == 37) { //left 
     a.style.left = parseInt(a.style.left) - 50 + 'px'; 
    } 
    if(e.keyCode == 39) { //right 
     a.style.left = parseInt(a.style.left) + 50 + 'px'; 
    } 
   } 
  } 
 </script> 
</body> 
</html> 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们