我正在尝试编写一个函数,只需单击一下按钮,即可将我的脸部图像从容器的一侧循环移动到另一侧。我需要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 -->
答案 0 :(得分:0)
更改
document.querySelector('button').onclick = start.play();
收件人
document.querySelector('button').onclick = start.play;
您应该仅将函数分配给onclick,而不调用它。否则,如果我们在解析时立即被调用。