当前位置 : 主页 > 网络编程 > JavaScript >

JS实现可以用键盘方向键控制的动画

来源:互联网 收集:自由互联 发布时间:2021-04-05
用JS写一个可以用键盘方向键控制的动画: 效果如下: 好了,代码如下: !DOCTYPE htmlhtml lang="en"head meta charset="UTF-8" meta name="viewport" content="width=device-width, initial-scale=1.0" meta http-equiv="X-U

用JS写一个可以用键盘方向键控制的动画:

效果如下:

好了,代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>Document</title>
 <style>
  body {
   overflow: hidden
  }
  
  img {
   position: absolute;
   top: 0;
   left: 10px;
   width: 100px;
   height: 82px
  }
  
  .right {
   transform: rotateY(180deg)
  }
  
  .top {
   transform: rotateZ(45deg)
  }
  
  .bottom {
   transform: rotateZ(-45deg)
  }
 </style>
</head>

<body>
 <img src="./img//Blue ocean11.png" alt="" class="move-background">
 <script>
  var oImg = document.querySelector("img");

  /* 思路: */
  /* 监听键盘的事件(<- -> 上 下) */
  document.onkeydown = function(e) {
   e = e || window.event;

   var code = e.which || e.keyCode;
   var offset = 10;
   switch (code) {
    case 37:
     console.log("left");
     console.log('innerWidth',innerWidth,oImg.offsetLeft);
     oImg.className = "";
     var left = oImg.offsetLeft - offset;
     if (left <= -oImg.offsetWidth) {
      left = window.innerWidth;
     }
     oImg.style.left = left + "px";
     break;
    case 38:
     console.log("top");
     oImg.className = "top";
     var top = oImg.offsetTop - offset;
     if (top <= -oImg.offsetHeight) {
      top = window.innerHeight;
     }
     oImg.style.top = top + "px";
     break;
    case 39:
     console.log("right");
     oImg.className = "right";
     var left = oImg.offsetLeft + offset;
     if (left >= window.innerWidth) {
      left = -oImg.offsetWidth;
     }
     oImg.style.left = left + "px";
     break;
    case 40:
     console.log("bottom");
     oImg.className = "bottom";
     var top = oImg.offsetTop + offset;
     if (top >= window.innerHeight) {
      top = -oImg.offsetHeight;
     }
     oImg.style.top = top + "px";
     break;
    default:
     break;
   }

   /* 临界值检查 */
  }
 </script>
</body>

</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

网友评论