Why is my animation “replayed” when an element is added via innerHTML?

你离开我真会死。 提交于 2019-12-10 13:39:52

问题


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


回答1:


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>');


来源:https://stackoverflow.com/questions/34401219/why-is-my-animation-replayed-when-an-element-is-added-via-innerhtml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!