我正在寻找使用jQuery预加载图像的最佳方法。
我尝试使用此代码,但它似乎不起作用:
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/preload.jpg'
]);
这是我的标记:
<div class="item">
<img src="img/lookbook_item1.jpg" alt="lookbook_item1" width="187" height="259">
</div>
<div class="item">
<img src="img/lookbook_item1.jpg" alt="lookbook_item1" width="187" height="259">
</div>
<div class="item">
<img src="img/lookbook_item2.jpg" alt="lookbook_item2" width="383" height="259">
</div>
我不想使用插件,只是一个可以执行fadeIn或类似操作的小脚本。
答案 0 :(得分:2)
以这种方式尝试:
$.each( arrayOfImages, function( i, src ) {
var img = new Image()
img.src = src;
img.load = function() {
$("img[src=" + src + "]").fadeIn();
};
});
答案 1 :(得分:0)
试试这个
HTML
<div class="item">
<img src="placeholder.gif" data-src="img/lookbook_item1.jpg" alt="lookbook_item1" width="187" height="259">
</div>
<div class="item">
<img src="placeholder.gif" data-src="img/lookbook_item2.jpg" alt="lookbook_item1" width="187" height="259">
</div>
<div class="item">
<img src="placeholder.gif" data-src="img/lookbook_item3.jpg" alt="lookbook_item1" width="187" height="259">
</div>
jQuery的:
$(function() {
var urls = $('.item img').each(function () {
var img = new Image();
var src = $(this).data("src");
img.onload = function () {
$("img[data-src=" + src + "]").attr("src",src).fadeIn();
};
img.src = src;
});
});