JavaScript触发的CSS动画首次使用后失效问题
解决CSS翻转动画二次点击不播放的问题
问题核心
使用animation-fill-mode: forwards会让元素停在动画结束状态,二次点击时元素已处于反向动画的起始位置,浏览器判定无需执行动画;同时.unflip类存在CSS属性名错误,且直接切换类无法触发浏览器重新执行动画。
解决方案
通过新增反向动画关键帧、重置元素状态并强制重绘的方式,确保每次点击都能触发动画:
修正后的CSS
* { perspective: 1600px; } #postCard { transform-style: preserve-3d; width: 400px; height: 250px; position: relative; transform: rotateY(0deg); /* 明确初始状态 */ } .cardSize { background-color: floralwhite; width: 100%; height: 100%; -webkit-backface-visibility: hidden; backface-visibility: hidden; } .flip { animation: 0.5s cubic-bezier(.19, 1, .22, 1) forwards infoOut; -webkit-animation: 0.5s cubic-bezier(.19, 1, .22, 1) forwards infoOut; } .unflip { animation: 0.5s cubic-bezier(.19, 1, .22, 1) forwards infoIn; -webkit-animation: 0.5s cubic-bezier(.19, 1, .22, 1) forwards infoIn; } form p { text-align: center; font-variant: small-caps; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; text-shadow: 0px 1px 0px white; } #postCard .back { position: absolute; top: 0px; transform: rotateY(180deg); } @keyframes infoOut { from { transform: rotateY(0deg); } to { transform: rotateY(180deg); } } @keyframes infoIn { from { transform: rotateY(180deg); } to { transform: rotateY(0deg); } } #spinMode { position: absolute; top: 4px; left: 4px; }
修正后的JavaScript
function setup() { card = document.getElementById("postCard"); document.getElementById("spinMode")?.addEventListener("click", spinMode); } let card; let contactSide = false; function spinMode() { // 移除所有动画类,重置元素状态 card.classList.remove("flip", "unflip"); // 强制浏览器重绘,确保状态重置生效 void card.offsetWidth; contactSide = !contactSide; card.classList.add(contactSide ? "flip" : "unflip"); } window.addEventListener("load", setup);
关键修改说明
- 新增反向动画关键帧:创建
infoIn关键帧专门处理从180deg转回0deg的动画,替代易出问题的animation-direction: reverse。 - 重置并强制重绘:每次切换动画前先移除所有动画类,再通过
void card.offsetWidth触发浏览器重绘,确保元素回到初始状态后再添加新动画类,触发动画播放。 - 修正CSS错误:去掉动画时长前多余的0,修正属性名拼写错误。
内容的提问来源于stack exchange,提问作者world_sword
相关产品推荐
相关产品推荐

