1

我正在寻找使用 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>

我不想使用插件,只是一个可以执行淡入淡出或类似操作的小脚本。

4

2 回答 2

2

试试这种方式:

$.each( arrayOfImages, function( i, src ) {
  var img = new Image()
  img.src = src;
  img.load = function() {
    $("img[src=" + src + "]").fadeIn();
  };
});
于 2013-05-04T15:56:56.133 回答
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;
    });
 });
于 2013-05-04T16:38:25.147 回答