亲宝软件园·资讯

展开

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

KindleYoung 人气:0

用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>

加载全部内容

相关教程
猜你喜欢
用户评论