用javascript多次触发CSS3关键帧

时间:2016-01-31 12:51:09

标签: javascript animation

我使用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>

JSFIDDLE

每当我调用此函数时,我希望它能够动画。

5 个答案:

答案 0 :(得分:0)

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

根据this CSS-Tricks article

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";
}

答案 1 :(得分:0)

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

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>

答案 2 :(得分:0)

在正在播放动画的元素后面的body部分添加此代码 -

selected.map(function(item) {
   return item.name;
}).join(',')

或者如果您不想删除样式属性,因为您有其他css而不是动画,然后创建一个类并动态添加类并将其删除为上面的代码。

答案 3 :(得分:0)

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

JSFiddle

&#13;
&#13;
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);
});
&#13;
#box {
  background: red;
  width: 100px;
  height: 100px;
}
@keyframes box {
  50% {
    width: 300px;
  }
}
&#13;
<div id='box'><div>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

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

将数据集值更改为从未更改过的值,然后对该数据使用 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
    ? 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
    ? 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
03
14
04
...

第一个数字表示当前是否关闭,其余的都是一个计数器,每次都更新值。

相关问题