为什么我的动画“重放”当一个元素通过innerHTML? [英] Why is my animation "replayed" when an element is added via innerHTML?

查看:118
本文介绍了为什么我的动画“重放”当一个元素通过innerHTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小脚本,在点击我的页面上的按钮时使用 innerHTML 添加一个名为doge的div,在这个页面上有一个带有CSS的div关键帧动画。



但是,当我点击按钮在我的页面上添加名为doge的div时,CSS动画是重放。为什么?如何解决此问题?



  function addHtml(){document.getElementById(wow)。innerHTML + ='< div class = doge> such wow< / div>';}  

  @keyframes color {10%{background:#4CAF50; } 50%{background:#3F51B5; } 100%{background:#009688; }}。myDiv {background:#000; color:#fff; animation:color 1s;}。doge {background:#F57F17;}  

 < div id =wow> < div class =myDiv> Hi!< / div> < br> < button onclick =addHtml()>添加HTML!< / button>< / div>  

JSFiddle

解决方案

这是因为你修改所有的元素的HTML当你修改 .innerHTML 属性。



根据 MDN


.innerHTML - 删除所有元素


在这样做的时候,DOM假定 .myDiv 元素刚刚添加,这意味着动画将被重放。要解决此问题,请使用 .appendChild ()方法



更新示例

  var div = document.createElement('div' ); 
div.textContent ='such wow';
div.className + ='doge';
document.getElementById(wow)。appendChild(div);






或者, Teemu指出,您还可以使用 .insertAdjacentHTML()方法



更新示例

  document.getElementById(wow) .insertAdjacentHTML('afterend','< div class =doge> such wow< / div>'); 


I have a little script that adds a div named "doge" using innerHTML when clicking on a button on my page, and on this page there's a div with a CSS keyframes animation.

However, when I click on the button to add the div named "doge" on my page, the CSS animation is "replayed". Why? How can I fix that?

function addHtml() {
    document.getElementById("wow").innerHTML += '<div class="doge">such wow</div>';
}

@keyframes color {
    10% {
        background: #4CAF50;
    }
    50% {
        background: #3F51B5;
    }
    100% {
        background: #009688;
    }
}

.myDiv {
    background: #000;
    color: #fff;
    animation: color 1s;
}

.doge {
    background: #F57F17;
}

<div id="wow">
    <div class="myDiv">Hi!</div>
    <br>
    <button onclick="addHtml()">Add HTML!</button>
</div>

JSFiddle

解决方案

It's because you're modifying all of the element's HTML when you modify the .innerHTML property.

According to MDN:

.innerHTML - Removes all of element's children, parses the content string and assigns the resulting nodes as children of the element.

In doing so, the DOM assumes that the .myDiv element has just been added which means that the animation is going to be replayed. To work around that, use the .appendChild() method instead:

Updated Example

var div = document.createElement('div');
div.textContent = 'such wow';
div.className += 'doge';
document.getElementById("wow").appendChild(div);


Alternatively, as Teemu points out, you can also use the .insertAdjacentHTML() method:

Updated Example

document.getElementById("wow").insertAdjacentHTML('afterend', '<div class="doge">such wow</div>');

这篇关于为什么我的动画“重放”当一个元素通过innerHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆