javascript - 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">
解决方案
我为此使用了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">
推荐阅读
- arrays - Excel VBA:如何使用数组作为数据透视表的筛选条件
- bash - 根据 shell 中的另一个文件过滤一个文件中的特定行
- coldfusion - 在 Chrome/IE 中打开快捷方式 URL
- python - PySpark - 重命名存储为 CSV 文件中字符串列的 JSON 中的键名
- go - 寻找有损/无损 VP8X 比特流
- adapter - 如何在另一个 RecyclerView 的嵌套 RecyclerView 中显示可变数量的项目?
- java - 如何将一个整数的三位数字相加?
- database - 查询表达式 strUserPassword 中的语法错误
- javascript - Discord,js TypeError:member.guild.roles.find 不是函数
- php - Symfony,当我在主机 1and1 上将网站投入生产时出现错误 500