Home > Web Front-end > JS Tutorial > JS implements moving elements up, down, left, and right

JS implements moving elements up, down, left, and right

小云云
Release: 2018-01-09 13:29:16
Original
2984 people have browsed it

This article mainly introduces the effect of moving elements up, down, left and right with JS in detail. It has a certain reference value. Interested friends can refer to it. I hope it can help everyone.


<!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> 
 <p id="cell"></p> 
 <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 + &#39;px&#39;; 
     //注意要用parseInt 因为a.style.top类型是字符串 
    } 
    if(e.keyCode == 40) { //down 
     a.style.top = parseInt(a.style.top) + 50 + &#39;px&#39;; 
    } 
    if(e.keyCode == 37) { //left 
     a.style.left = parseInt(a.style.left) - 50 + &#39;px&#39;; 
    } 
    if(e.keyCode == 39) { //right 
     a.style.left = parseInt(a.style.left) + 50 + &#39;px&#39;; 
    } 
   } 
  } 
 </script> 
</body> 
</html>
Copy after login

Related recommendations:

JavaScript Select and Option list elements move up, down, left and right_Form special effects

Use js to get the content instance sharing of pseudo elements

detailed explanation of jQuery remove() filtering deleted elements

The above is the detailed content of JS implements moving elements up, down, left, and right. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template