IT码农库

您当前所在位置:首页 > 网络编程 > JavaScript

JavaScript

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

网络 KindleYoung2020-12-11JavaScript6551
这篇文章主要为大家详细介绍了JS实现可以用键盘方向键控制的动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

大图广告(830*140)