简体   繁体   English

单击按钮时播放 CSS 动画不起作用

[英]Playing CSS animation on button click won't work

I'm trying to call a CSS animation on the event that this button is pressed, after doing some research it seems classList is the way forward.我正在尝试在按下此按钮时调用 CSS 动画,经过一些研究后,似乎 classList 是前进的方向。 It's late and I think I'm being stupid but I cannot get it to work.很晚了,我认为我很愚蠢,但我无法让它发挥作用。

HTML: HTML:

<body>
<img id="myID" class="mouse" src="mouse.png" onclick="ani()">
<script src="script.js"></script>
</body>

<head>
<link href="styles.css" rel="stylesheet"/>
</head>

JavaScript: JavaScript:

function ani()
{
  document.getElementById('myID').classList.add = 'animate';
}    

CSS: CSS:

.animate
{
  animation: test 1s linear forwards;
}
@keyframes test
{
  100%
{
  transform: translateX(calc(8%));
}
}

add is a function so the way you are using classList needs a slight change from: add 是一个函数,因此您使用 classList 的方式需要从以下方面稍作更改:

document.getElementById('myID').classList.add = 'animate';

to:到:

document.getElementById('myID').classList.add('animate');

 function ani(){ document.getElementById('myID').classList.add('animate'); }
 .animate { animation: test 1s linear forwards; } @keyframes test { 100% { transform: translateX(calc(8%)); } }
 <body> <img id="myID" class="mouse" src="https://stock.wikimini.org/w/images/d/d4/Mickey_Mouse.png" onclick="ani()"> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM