gpt4 book ai didi

javascript - splice 不适用于 DOM 元素数组

转载 作者:行者123 更新时间:2023-11-28 14:26:06 25 4
gpt4 key购买 nike

我正在创建气泡效果,但在气泡到达顶部时移除气泡时遇到问题。气泡是圆形 svg 元素并存储在数组中。 splice 函数返回错误。您可以在 animateBubbles() 函数中看到它。我不确定我做错了什么。

SCRIPT438:对象不支持属性或方法“拼接”

let bubbles = [];

let bubblesC = [];

function createBubbles(n, x, y, w, h) {

for (let i = 0; i < n; i++) {

let circle = document.createElementNS(svgns, 'circle');

bubblesC[i] = Math.PI / (Math.random() * Math.floor(10));

let tmpX = x + getRandomInt(w);

circle.setAttribute('cx', tmpX);
circle.setAttribute('cy', getRandomInt(h)+wHeight);
circle.setAttribute('r', 3+getRandomInt(10));

circle.setAttribute("id", "bubble" + i);
circle.setAttribute("fill", "url(#grad3)");
circle.setAttribute("stroke", "light");
circle.setAttribute("opacity", "0.5");

bubbles.push(circle);

svg.appendChild(circle);

}

}

function animateBubbles() {

for (let i = 0; i < bubbles.length; i++) {

let bx = parseInt(bubbles[i].getAttribute("cx"));
let by = parseInt(bubbles[i].getAttribute("cy"));

bx += Math.round(2 * Math.sin(bubblesC[i]));
by += -2;

if (by < wavesY) {
bubbles[i].setAttribute("fill", "transparent");
bubbles[i].setAttribute("stroke", "white");
}

if (by < wavesY - 20) {
//by = getRandomInt(wHeight)+wHeight;
bubbles[i].setAttribute("fill", "url(#grad3)");
bubbles[i].setAttribute("stroke", "light");
bubbles[i].setAttribute("opacity", "0.5");
}

if (by < wavesY - 40) {

bubbles[i].splice(i, 1); ////////////////// THIS IS THE PROBLEM

//bubbles[i].parentNode.removeChild(bubbles[i]);

}

bubbles[i].setAttribute("cx", bx);
bubbles[i].setAttribute("cy", by);

bubblesC[i] += Math.PI / 8;

}

}

最佳答案

splice只能用于数组,不能用于对象。使用bubbles.splice(i, 1);

关于javascript - splice 不适用于 DOM 元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com