我想在图像标签之间添加延迟.我该怎么办



我的项目:jsFiddle

setTimeout(function() {

for (var i = 0; i < 15; i++) {

$('.rastgele').append('<img class="g59" src="https://cdn.intgrl.co/G59/static/images/window.png">');

}

$('.g59').each(function(index) {
$(this).css({
left: ((Math.random() * $('body').width())),
top: ((Math.random() * $('body').height())),
});
});

/*$('.g59').delay(5000).queue(function(next) {
$(this).show();
next();
});*/
}, 2000);

但它不起作用。我想喜欢https://g59records.com/我希望每个img标记之间有半秒。我添加了延迟,我使用了setTimeout或setInterval,但它对我不起作用。伙计们,我能做什么?请帮帮我。抱歉我英语不好。

您需要使用setInterval来一次又一次地调用它,而不是setTimeout。

var imagesOnWindow=20;
var i=1;
var start
start = setInterval(function() {
var left=((Math.random() * $('body').width()));
var top=((Math.random() * $('body').height()));
var _img=$("<img/>",{
class:"g59",
src:"https://cdn.intgrl.co/G59/static/images/window.png",
});
$(_img).css('top', top);
$(_img).css('left', left);
console.log(_img);
$('.rastgele').append(_img);
i++;
if(i>imagesOnWindow)
clearInterval(start);
}, 1000);

你可以在这里看到一个工作示例

不需要for循环,当计数器达到15时,可以设置间隔和停止间隔。

var counter = 0;
var intervalId = setInterval(function() {
if (counter > 15) {
clearInterval(intervalId);
return false;
}
var img = document.createElement("img");
img.src = "https://cdn.intgrl.co/G59/static/images/window.png";
img.className = "g59";
$('.rastgele').append(img);
$(img).css({
left: ((Math.random() * $('body').width())),
top: ((Math.random() * $('body').height())),
});
counter++;
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rastgele"></div>

尝试使用这个:

for (var i = 0; i < 15; i++) {
(
function(i) {setTimeout(function() {
var left = Math.random() * $('body').width();
var top = Math.random() * $('body').height();
$('.rastgele').append('<img class="g59" style="left:'+left+'px;top:'+top+'px;" src="https://cdn.intgrl.co/G59/static/images/window.png">');
}, 500*i)
})(i);  
}

最新更新