多次使用 javascript 触发 CSS3 关键帧

Triggering CSS3 Keyframes with javascript multiple times

本文关键字:触发 CSS3 关键帧 javascript      更新时间:2023-09-26

>我正在使用javascript触发CSS3关键帧,但它适用于此后的第一次调用,对该函数的任何调用都不会使我的div动画化。

这里是Javascript代码

function animateShare (imgSrc){            
    var share = document.getElementById("shareTools");
    share.style.animation = "testAnimate 1s ease-in-out 0s"
    //shareTools.style.animationPlayState = "running";
}

问题示例(单击红色框进行预览)

var box = document.getElementById("box");
function animateBox(){
    box.style.animation = "box 1s ease-in-out 0s";
  }
#box{
  background:red;
  width:100px;
  height:100px;
  }
@keyframes box {
    50%{width:300px;}
  }
<div id='box' onclick='animateBox()'><div>

吉斯菲德尔

我希望每次调用此函数时它都进行动画处理。

您可以使用众所周知的hack:销毁并创建元素来重置动画

var box = document.getElementById("box");
function animateBox(){
    //destroy and create hack
    document.body.removeChild(box);
    document.body.appendChild(box);
    box.style.animation = "box 1s ease-in-out 0s";
  }
#box{
  background:red;
  width:100px;
  height:100px;
  }
@keyframes box {
    50%{width:300px;}
  }
<div id='box' onclick='animateBox()'><div>

如果有人仍然对此感兴趣,还有另一个有效的技巧:

将数据集值更改为从未有过的值,然后对该数据使用 css 匹配。

我在动画菜单的折叠/取消折叠时使用了这种技术,当然可以多次发生。这是我是如何做到的:

#menu[data-closed^="1"]{
    animation:menu_closing;
}
#menu[data-closed^="0"]{
    animation:menu_opening;
}

因此,动画基于数据集的第一个字符(1 或 0)。

然后在想要关闭/打开菜单的点击事件中:

var closed = menu_ele.dataset.closed // closed right now
    ? parseInt( menu_ele.dataset.closed.substr(0,1) )
    : 0; // assuming menu is initialized open
var counter = menu_ele.dataset.closed // nb of times the menu was closed or open
    ? parseInt( menu_ele.dataset.closed.substr(1) )
    : 0;
menu_ele.dataset.closed = ''+(1-closed)+(counter+1);

这样,"封闭"数据集变量在每次点击时都会像这样变化:

11 (closing for the first time)
02 (reopening for the first time)
13
04
15
06
...

第一个数字指示它当前是否关闭,而其余所有数字都是一个计数器,每次都使值更新。

想想你的代码 - 第一次调用它什么都不做,因为它已经改变了该元素的动画属性。

根据这篇CSS-Tricks文章:

function animateShare (imgSrc){            
    var share = document.getElementById("shareTools");
    share.style.animation = "testAnimate 1s ease-in-out 0s";
    shareTools.style.animationPlayState = "paused";
    shareTools.style.animationPlayState = "running";
}

播放动画的元素之后的正文部分添加此代码-

<script>
document.getElementById('shareTools').addEventListener("animationend", function () {
        this.removeAttribute("style");
    })
</script>

或者,如果您不想删除样式属性,因为您有动画以外的其他 css,那么创建一个类并动态添加类并将其删除,如上面的代码所示。

只需在

动画完成后从元素的样式中删除 animation 属性即可重置动画 - 无需删除元素。在我的示例中,我在 JS 中设置了持续时间,但您也可以轻松添加 animationend 钩子以使其更简单。

JSFiddle

var duration = 1000;
document.getElementById('box').addEventListener('click', function onClick(ev) {
  var el = this;
  el.style.animation = 'box ' + (duration / 1000 + 's') + ' ease-in-out';
  setTimeout(function() {
    el.style.animation = ''
  }, duration);
});
#box {
  background: red;
  width: 100px;
  height: 100px;
}
@keyframes box {
  50% {
    width: 300px;
  }
}
<div id='box'><div>