[英]Showing a loading image before an image is loaded with jQuery?
我在 SO 上關注了幾個不同的類似問題,但由於某種原因它不起作用。 有人可以幫我理解為什么嗎? 我希望首先顯示加載圖像,然后在加載更大的圖像時淡出。 較大的圖像應該淡入。
小提琴: http : //jsfiddle.net/95rpu029/2/
HTML
<article class="project">
<img width="375" height="375" src="http://dummyimage.com/375x375/000/fff" class="attachment-home-thumb">
</article>
JS
// Show loading image
$('article').prepend('<span class="loading-icon"><img src="http://i.imgur.com/lJpvTU3.gif" height="32" width="32" alt="Loading..."></span>');
// main image loaded ?
$('article img').on('load', function(){
// hide/remove the loading image
$('.loading-icon').fadeOut();
$('article').show();
});
CSS
article.project {
display: none;
float: left;
margin: 0 1% 2%;
max-width: 375px;
overflow: hidden;
position: relative;
width: 23%;
}
article.project img {
display: block;
margin: 0;
padding: 0;
max-width: 100%;
height: auto;
}
發生這種情況是因為您的測試圖像非常小,並且在您的代碼有機會運行之前已經加載。 所以load
不會被觸發(因為圖像已經加載)。 我對您的代碼做了一些小改動並更新了fiddle 。 變化如下:
Image
對象並連接該對象的onload
當事件發生時,將源分配給原始圖像
var im = new Image(); im.onload = function () { $("#img2Replace")[0].src = im.src; }; im.src = "http://dummyimage.com/375x375/000/fff";
那么現在我們必須為每個圖像執行此操作:
var imgs = $("article.project img.attachment-home-thumb");
$.each(imgs, function () {
var $this = $(this);
var im = new Image();
im.onload = function () {
var theImage = $this;
$this.hide("slow");
theImage[0].src = im.src;
$this.show('fast');
};
im.src = $this.data("mainsrc");
});
請注意,為了模擬加載實際圖像的延遲,我在小提琴中使用了setTimeout
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.