javascript - 使用javascript在每次点击时触发动画
问题描述
我正在尝试使用 CSS 动画翻转卡片。现在它可以工作,但只能在第一次单击按钮时使用。本质上,我的用例是:点击按钮,翻转卡片。点击按钮,翻转卡片等。
function nextCard(){
document.getElementById('card').addEventListener("click",flipTheCard());
}
function flipTheCard(){
document.getElementById('card').classList.add('newCard');
}
动画通过向卡片添加一个类来工作。
.newCard {
animation: flip 1.5s;
transform-origin: 50% 100% 0;
}
我已经尝试在动画之后删除该类并在每次单击时重新添加它,但这只是让它完全停止工作。
有什么想法或更好的方法吗?不确定添加和删除动画类是否是最佳实践。
谢谢!
解决方案
只需用您的代码替换它,它就会正常工作(您期望它的工作方式)
const card = document.getElementById('card')
function nextCard(){
card.addEventListener("click",flipTheCard);
}
function flipTheCard(){
card.classList.add('newCard');
setTimeout(()=> {
card.classList.remove('newCard')
},1500)
}
以下是反映您的问题的小例子
const btn = document.querySelector('.btn')
const box = document.querySelector('.box')
btn.addEventListener('click', () => {
box.classList.add('animate')
setTimeout(() => {
box.classList.remove('animate')
},1500)
})
.box{
width: 100px;
height: 100px;
background-color: blue;
margin: auto;
margin-top: calc(100vh - 60vh);
}
.box.animate{
animation: spin 1.5s forwards;
}
@keyframes spin{
0%{
transform: rotate(0deg);
}
100%{
transform: rotate(360deg);
}
}
<div class='box'></div>
<button class="btn">click</button>
推荐阅读
- react-native - 如何从静态 PNG 图像创建具有 12 个步骤(每个 30 度)的微调器动画?
- react-native - 使用 React Native 和 Expo 进行 MIDI 通信
- ubuntu - Ubuntu 上的 Tomcat SSL 配置
- python - ValueError: no enough values to unpack (expected 2, got 1) 使我无法完成我的代码
- python - Pip 在 Artifactory 中找不到 PyPI 包
- fortran - 在fortran中使用MPI_PUT,不同等级使用c_loc有不同的位移
- django - python_ldap | 在变量中提供证书内容
- java - 如何从Android中的自定义位置编号加载webView
- java - 在 Java 8 计算其值后返回映射键的方法
- javascript - ag-grid CellEditor 单元格高度不正确