拼接不适用于DOM元素数组

时间:2018-11-06 14:17:47

标签: javascript svg

我正在创建气泡效果,但是在气泡到达顶部时删除气泡存在问题。气泡是圆形svg元素,并存储在数组中。拼接函数返回错误。您可以在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;

    }

}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

Array.splice()删除从给定索引开始的给定数量的元素,所有其余元素向下移动。然后for-loop的事后程序块将i递增1,以便跳过索引。

看看:

let fiboArray  = [ 1, 1, 2, 3, 5, 8 ];

// Array.splice() fails in forward for loops
for (let i = 0; i <= fiboArray.length ; i++) {
    if (fiboArray[i] === 1) {
        fiboArray.splice(i, 1);
    }
}
console.log(fiboArray); // → [ 1, 2, 3, 5, 8 ]

后向for循环可以处理这种特殊行为

let fiboArray  = [ 1, 1, 2, 3, 5, 8 ];

// Array.splice() with backward for loops
for (let i = fiboArray.length - 1; i >= 0; i--) {
    if (fiboArray[i] === 1) {
        fiboArray.splice(i, 1);
    }
}
console.log(fiboArray); // → [ 2, 3, 5, 8 ]

但是正如之前回答的那样:splice()仅可用于Array

更改

bubbles[i].splice(i, 1);

bubbles.splice(i, 1);