0

我想要的是当第一个(.goccia)元素到达屏幕底部时,设置间隔功能停止。

function spostaGocce(){
var goccia = document.querySelectorAll('.goccia');
for(i = 0; i < goccia.length; i++){ 
goccia[i].style.top = parseInt(goccia[i].style.top ||0) + Math.round(Math.random() * 2) + 1 
+ 'px';
}
}
function muoviti(){
setInterval(spostaGocce, 30);
}
document.querySelector('button').addEventListener('click', muoviti);

我试图创建一个这样的变量:

gocciaTop = goccia.getBoundingClientRect().top

然后像这样做一个“如果”:

if(gocciaTop == window.innerHeight){
document.write('done')
}

但他给了我一个错误,说“getBoundingClientRect() 不是函数”。

4

2 回答 2

1

你可以使用clearInterval()功能。例如在你的情况下。您将创建一个变量

var intervalId;

然后在您的muoviti()函数中,您将为您分配setInterval对上述变量的引用。

function muoviti(){
  intervalId = setInterval(spostaGocce, 30);
}

然后一旦你完成了,就像在以下if情况下这样做:

if(gocciaTop == window.innerHeight){
  clearInterval(intervalId);
  document.write('done')
}
于 2020-02-26T09:08:38.433 回答
0

if 条件和变量 gocciaTop 应该在 for 循环内。

function spostaGocce(){
    var goccia = document.querySelectorAll('.goccia');
    for(i = 0; i < goccia.length; i++){ 
        goccia[i].style.top = parseInt(goccia[i].style.top ||0) + Math.round(Math.random() * 2) + 1 
        + 'px';
        var gocciaTop = goccia[i].getBoundingClientRect().top;

        if(gocciaTop == window.innerHeight){
         clearInterval(Int);
        }
    }
}
var Int;

function muoviti(){
    Int = setInterval(spostaGocce, 30);
}

document.querySelector('button').addEventListener('click', muoviti);
于 2020-02-26T09:23:34.767 回答