免责声明:我是个菜鸟。请耐心等待;)
我正在开发一个使用 CSS 动画并使用 JS 操作 DOM 的小项目。通过单击动画元素,它们将从 DOM 中删除。 删除所有项目后,将添加视频元素。
后者是我正在努力解决的问题。元素已从 DOM 中删除,但 cat 数组的长度不会更新,因此它永远不会达到 0(当添加视频时)。 这是我的项目的摘录: https://codepen.io/miliberlin/pen/BaawrKg
(PS:如果有人也可以帮助我找出为什么 .cat:hover {transform:rotate(360deg);} 在我的 CSS 文件中不起作用,我将永远感激不已)
for (i = 0; i < cat.length; i++) {
cat[i].addEventListener('click', function() {
this.parentNode.removeChild(this);
});
}
if (cat.length === 0) {
const iframe = document.createElement("iframe");
iframe.src = "https://www.youtube.com/embed/SB-qEYVdvXA";
iframe.width = "560";
iframe.height = "315";
document.getElementById("wrapper").appendChild(iframe);
}
最佳答案
在这种情况下,最好使用 DOM 上的实时 View HTMLCollection
,而不是从静态的 querySeletorAll
返回的 NodeList
.
此外,JavaScript 不是响应式的,因此 if (cat.length === 0) {...}
中的代码不会在 cat
时神奇地运行是空的。当发生这种情况时,你必须自己调用它:
const cat = document.getElementsByClassName("cat");
for (let i = 0; i < cat.length; i++) {
cat[i].addEventListener('click', function() {
this.parentNode.removeChild(this);
if (cat.length === 0) {
whenCatEmpty()
}
});
}
function whenCatEmpty() {
const iframe = document.createElement("iframe");
iframe.src = "https://www.youtube.com/embed/SB-qEYVdvXA";
iframe.width = "560";
iframe.height = "315";
document.getElementById("wrapper").appendChild(iframe);
}
If anybody can also help me figure out why .cat:hover {transform: rotate(360deg);} isn't working
您在动画和 .cat:hover
中都使用了 transform
。 CSS 声明会互相覆盖。您可以使用 top
属性在动画中移动猫(这比 transform:translate
性能较差,但我没有看到任何其他方法可以使其与 一起使用>变换:旋转
@keyframes motion{
to{ top: 1500px }
}
关于javascript - 删除元素后更新数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58623557/