[英]Create & Show images as background-image one by one - JavaScript
Problem statement - I need to create & show multiple images dynamically from my directory one by one, with transform - scale ( for showing ) applied to it. 问题陈述 - 我需要逐个从我的目录动态创建和显示多个图像,并应用变换 - 缩放(用于显示)。 But my code is showing them together at once. 但是我的代码立即将它们展示在一起。
HTML: HTML:
<div class="images-cont">
</div>
CSS: CSS:
a {
border-radius: 50%;
width: 120px;
height: 160px;
transform: scale(0,0);
transition: all 4s;
background:no-repeat center center;
display:inline-block;
}
a.scale{ transform: scale(1,1);}
JS: JS:
$("document").ready(function(){
var minImages = 1; // Images are numbered from 1.jpg till 10.jpg
var maxImages = 10;
for(i=1;i<=maxImages;i++){
buildImageLink();
}
showImages();
function buildImageLink(){
var anchor = $(document.createElement('a'));
anchor.attr('href','#').appendTo('.images-cont');
loadImage(anchor);
};
function loadImage(elem){
var f = new Image;
var p = 'images/' + i + '.jpg'; // Location of the images directory
f.src = p;
f.addEventListener("load", function() {
elem.css({ 'background-image': 'url('+ p +')'});
});
};
function showImages(){
$('.images-cont a').each(function(){
$(this).delay(1000).addClass('scale')
})
}
});
Have gone through a number of posts in SO itself, and refined my code accordingly, but its still the same. 已经通过SO本身的一些帖子,并相应地改进了我的代码,但它仍然是相同的。 I am not understanding what I am missing here. 我不明白我在这里缺少什么。 The delay is just not happening. 延迟就是没有发生。
.delay()
does not apply to .addClass()
, only to animation queues .delay()
不适用于.addClass()
,仅适用于动画队列
What you want is probably a setTimeout function: 你想要的可能是一个setTimeout函数:
function showImages(){
$('.images-cont a').each(function(i, el){ // `i` is Index, `el` is HTMLElement object
setTimeout(function(){
$(el).addClass('scale');
}, i * 1000); // (0*1000=0; 1*1000=1000, 2*1000=2000 etc)
})
}
Also, instead of var anchor = $(document.createElement('a'));
另外,代替var anchor = $(document.createElement('a'));
you can do: 你可以做:
var anchor = $("<a />");
or even: 甚至:
var anchor = $("<a />", {href:"#"});
/* and than just: */ anchor.appendTo('.images-cont');
Also it's suggested to change the order: 还建议更改顺序:
f.addEventListener("load", function() {
elem.css({ 'background-image': 'url('+ p +')'});
});
f.src = p; // After instantiating the load function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.