当元素已被另一个元素替换时,对动画进行计数

时间:2018-10-19 13:52:01

标签: javascript html css

如果我有一个元素,它具有CSS动画。

3秒后,JavaScript用另一个新元素(但相同的div元素)替换了该元素。

我希望新元素继续动画的其余未完成部分,但不重新启动动画。

有可能实现吗?

function replaceDIV(){
    var elm = document.getElementsByTagName("div")[0];
    var new_elm = document.createElement("div");
    new_elm.innerHTML = "New Element";
    new_elm.style.backgroundColor = "green";
    elm.parentNode.replaceChild(new_elm,elm);
}
setTimeout(function(){
    replaceDIV();
}, 3000);
div {
    color: #FFF;
    width: 150px;
    height: 150px;
    position: relative;
    -webkit-animation: mymove 8s linear forwards;
    animation: mymove 8s linear forwards;
}

@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 500px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 500px;}
}
<div style="background-color: red;">Original Element</div>

在DIV更改为新的DIV之后,如何继续其余未完成的CSS动画?

是否可以仅使用CSS来实现?还是必须使用Javascript?

1 个答案:

答案 0 :(得分:0)

对容器div进行动画处理,然后换出内部div,将使您获得所需的解决方案。

问题在于,当您换出相同的dom元素时,它会有效地将CSS动画重置为开头-但是,如果您对容器进行动画处理并换出内部元素,则不会中断任何操作。

在以下代码段I中:

  • 已创建.container-div
  • 已将更新的CSS应用于该容器div
  • var elm声明的更新索引

function replaceDIV(){
    var elm = document.getElementsByTagName("div")[1];
    var new_elm = document.createElement("div");
    new_elm.innerHTML = "New Element";
    new_elm.style.backgroundColor = "green";
    elm.parentNode.replaceChild(new_elm,elm);
}
setTimeout(function(){
    replaceDIV();
}, 3000);
.container-div {
    color: #FFF;
    width: 150px;
    height: 150px;
    position: relative;
    -webkit-animation: mymove 8s linear forwards;
    animation: mymove 8s linear forwards;
}

@-webkit-keyframes mymove {
    from {left: 0px;}
    to {left: 500px;}
}

@keyframes mymove {
    from {left: 0px;}
    to {left: 500px;}
}
<div class="container-div"><div style="background-color: red;">Original Element</div></div>