0

此代码有效,但它是一种在加载图像后显示图像的有效方法吗?

LightBoxNamespace.SetupLightBox = function(path, lightBox) {

    // Create a new image.
    var image = new Image();

    // The onload function must come before we set the image's src, see link for explanation.
    // http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called.

    // Anonymous function set to onload event, to make sure we only proceed if the image has been loaded.
    image.onload = function () {

      if ($('#image').length) {
        $('#image').attr('src', path); // If the element already exists, change the src to our loaded image. 
      }
      else {
        $('<img id="image" alt="">').attr('src', path).insertAfter('#close'); // If the element does not exist, insert the full image html into the lightbox.
      }

      LightBoxNamespace.CentreBoxInViewport(lightBox);
      LightBoxNamespace.ShowOverlay(lightBox);
    };

    // Set the src, and show the image.
    image.src = path;
  };
4

2 回答 2

1
  var img = $('<img>');
  img.load(function(){alert("image loaded!")});
  img.attr('src', "url");
  if (!! img) img.appendTo('#close');

http://jsfiddle.net/W57QR/4/

于 2013-09-06T09:43:19.247 回答
0

“jQuery 方式”:

var $img = $('<img/>').prop({ src: path });

$img.load(function() { 
    console.log('image loaded correctly'); 
    $(this).insertAfter('#close'); 
}).error(function() { 
    console.log('error loading image'); 
});
于 2013-09-06T09:06:02.170 回答