只将 CSS 类应用于 innerHTML 元素一次

问题描述 投票:0回答:1

我有2个文件:

  • data.php
  • 页面.php

data.php 从 sql 数据库中获取一行并将其发送到 page.php

在 page.php 中,我还有一个 JS 脚本,它通过 AJAX 接收这一行,然后通过这个 js 脚本的 innerHTML 函数将这一行动态添加到 html 表中。

在使用 innerHTML 动态添加行时,我还添加了一个 css 类,用于闪烁/闪烁添加的行。这一切都有效,如果我插入第 2、3、4...行,还有插入的 previuos 闪烁以及如何让它们在添加到表时独立闪烁?

这是 css 类和动画

       @keyframes flash {
            from {
                background-color: #ffab91;
            }

            to {
                background-color: none;
            }
        }

        .flash_animation {
            animation: flash 1s 1;
        }

这是 JS 函数

 var html_part = document.getElementById("dynamic");
 html_part.innerHTML += "<tr id="flashing_row" class='flash_animation'><td>" + code + "</td><td>" +      name +"</td></tr>";

我希望 id="flashing row" 的 tr 独立应用 flash_animation 类

please check this image here

javascript php html css ajax
1个回答
0
投票

在插入新的之前,您应该从先前添加的行中删除动画类

例如

var rows = document.querySelectorAll("#dynamic .flash_animation"); rows.forEach(函数(行){ row.classList.remove("flash_animation"); });

演示:

document.querySelector("#test").addEventListener("click", function() {
  var code = "this is a test";
  var name = "demo";
  var rows = document.querySelectorAll("#dynamic .flash_animation");
  rows.forEach(function(row) {
    row.classList.remove("flash_animation");
  });
  var html_part = document.getElementById("dynamic");
  html_part.innerHTML += "<tr id=\"flashing_row\" class='flash_animation'><td>" + code + "</td><td>" + name + "</td></tr>";
});
@keyframes flash {
  from {
    background-color: #ffab91;
  }

  to {
    background-color: none;
  }
}

.flash_animation {
  animation: flash 1s 1;
}
<table id="dynamic">
</table>
<button id="test">
New row
</button>

© www.soinside.com 2019 - 2024. All rights reserved.