首页 > 解决方案 > JS setTimeout 运行后将图像移回

问题描述

我正在尝试更改图像的变换属性,使其在其起始位置和由函数更改的新位置之间来回摆动。它运行一次然后停留在那里,我假设它是因为我没有指定如何或何时返回。任何帮助表示赞赏。这是我的 JS 代码

function moveHands() {
var handLeft = document.getElementById("metalHand2");
var handRight = document.getElementById("metalHand");

handLeft.style.transform = "translateX(12px) scaleX(-1)";
handRight.style.transform = "translateX(12px)";

setTimeout(moveHands, 1283.42);

}

document.getElementById("playBtn").addEventListener("click", moveHands);

这是我的 HTML

<div id="flexBox2">
  <div id="picContainer">
    <img src="hand.jpg" alt="metal hand" id="metalHand">
  </div>
  <div id="picContainer2">
    <img src="hand.jpg" alt="metal hand" id="metalHand2">
  </div>
</div>

<input type="button" value="Play" id="playBtn">

标签: javascripthtmlsetsettimeoutintervals

解决方案


我为此使用了CSS Animation 属性

animation: 2s moveit linear infinite;

这意味着线性动画运行线性无限使动画连续循环

function moveHands() {
    $('#metalHand2').addClass("animating");
    $('#metalHand').addClass("animating");
};

document.getElementById("playBtn").addEventListener("click", moveHands);
#metalHand2.animating{
  animation: 2s moveit linear infinite;
}
#metalHand.animating{
  animation: 2s moveit linear infinite;
}
@keyframes moveit{
  from{
      transform:translateX(15px);
  }to{
    transform:translateX(0px);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="flexBox2">
  <div id="picContainer">
    <img src="https://images.unsplash.com/photo-1547014751-009831e5bc73?ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" alt="metal hand" id="metalHand" width="100">
  </div>
  <div id="picContainer2">
    <img src="https://images.unsplash.com/photo-1546872863-e85d5c3e5159?ixlib=rb-1.2.1&auto=format&fit=crop&w=1000&q=80" alt="metal hand" id="metalHand2" width="100">
  </div>
</div>

<input type="button" value="Play" id="playBtn">


推荐阅读