为什么通过 innerHTML 添加元素时我的动画 "replayed"?

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

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

但是,当我在我的页面上单击添加名为 "doge" 的 div 按钮时,CSS 动画是 "replayed"。为什么?我该如何解决?

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

这是因为当您修改 .innerHTML 属性 时,您正在修改所有元素的 HTML。

根据MDN

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

这样做时,DOM 假设刚刚添加了 .myDiv 元素,这意味着将要重播动画。要解决此问题,请改用 .appendChild() method

Updated Example

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

或者,如 , you can also use the .insertAdjacentHTML() method:

Updated Example

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