如何使用 JS 单击按钮循环自动移动图像?



我正在尝试编写一个函数,只需单击一个按钮,就可以循环地将我的面部图像从容器的一侧移动到另一侧。我需要 JavaScript 中的一个函数,它可以自动移动/动画对象(图像(以在我的容器中水平移动。每次我单击开始按钮甚至刷新页面时,我什至无法移动我的图像。我被困住了,帮助将不胜感激。我的代码在下面,所以我可以得到反馈。我的Javascript,html和css在单独的文件中。

var start = anime({
targets: 'img.face',
translateX: [{
value: 100,
duration: 1200
},
{
value: 0,
duration: 800
}
],
rotate: '1turn',
duration: 2000,
loop: true
});
document.querySelector('button').onclick = start.play();
<!-- language: lang-css -->
body {
text-align: center;
}
button {
color: red;
background: lightblue;
font-family: Impact, 'Arial Narrow Bold', sans-serif;
}
.face {
position: relative;
width: 50px;
height: 50px;
}
#container {
position: absolute;
width: 1000px;
height: 500px;
background: aqua;
border: 20px lightpink solid;
margin: 20px 150px 20px 150px;
}
<!-- language: lang-html -->
<div>
<button id="start">Start</button>
</div>
<div id="container">
<img class="face" src="https://previews.123rf.com/images/jemastock/jemastock1705/jemastock170504269/77700505-color-pencil-cartoon-front-view-face-guy-with-hairstyle-vector-illustration.jpg" alt="">
</div>
<!-- end snippet -->

更改

document.querySelector('button').onclick = start.play();

document.querySelector('button').onclick = start.play;

您应该只将函数分配给 onclick,而不调用它。否则,如果我们在解析时立即被调用。

最新更新