0

我正在使用模式窗口在缩略图上显示图片。
但是,调整大小的照片并未加载到模态窗口中。

图像的 src 最初不在我的标记中,但我通过动态附加将其添加到标记中。我第二次单击它,图片在模态中加载。

查看控制台时,我能够第一次获得高度和宽度。第二次我得到高度和宽度加上“图像已加载”文本。

我想检查一下照片是否已加载以及是否已完成,然后执行其余代码。如果未加载,请继续检查直到加载,然后继续执行其余代码。

我读过其他关于堆栈溢出的文章,但没有一篇对我有用。可以请一些帮助。

 $(document).ready(function() {

    function galleryStart ($current) {


       var $tImage      = $current.find('img');
       var fullURL        = $tImage.attr('src');
       var $dFigure         = $('#dialog-media figure .media');
       var fullSrcURL = "images/mypicture"; 
       var fullSrcURL = fullURL.replace(".jpg", "_full.jpg"); 


       var image;

      function onload () {
        console.log(image.height, image.width);
        var objHeight = image.height;
      var objWidth = image.width;
      }

      image= new Image();
      image.src=fullSrcURL;

      if (image.complete) {
         console.log('image already loaded to browser');
         onload();
      } else {

         image.onload = onload;
         console.log('xxx');
      }

    $dFigure.append('<img id="dialog-media-object" src="' + fullSrcURL + '" alt="' +         $tImage.attr('alt') + '" />');

   //Execute more code here once the image has finished loading
   //More code to load the image into the modal window
}

$('a.dialog-media').click(function (event) {
    event.preventDefault();

            $("#dialog").dialog({
          height: "auto",  //720
          width: "auto",   //960
          draggable: false,
          modal: true,
          //position: {
          //          my: "center", 
          //          at: "center",
          //          of: window },
          open: function(event, ui){
              galleryStart(tLink);
          },
         close: function(event, ui){
              galleryEnd();
      $(this).dialog('destroy').remove();


});

}); // 最后的结束标签

4

2 回答 2

1

您可以对图像使用 onload 事件,如下所示:

image= new Image();
image.onload = onLoadHandler;
image.src=fullSrcURL;

function onLoadHandler() {
    alert("Image is loaded!");
}

注意:在分配源之前将 分配onLoadHandler给很重要。image.onload

因此,在您的情况下,我会跳过整个image.complete语句并执行以下操作:

var $dFigure = $('#dialog-media figure .media');
var fullSrcURL = "images/mypicture"; 
var image;

function onload () {
  console.log(image.height, image.width);
  var objHeight = image.height;
  var objWidth = image.width;
  $dFigure.append('<img id="dialog-media-object" src="' + fullSrcURL + '" alt="' + $tImage.attr('alt') + '" />');
}

image= new Image();
image.onload = onload;
image.src=fullSrcURL;
于 2013-10-03T18:58:14.060 回答
0

只需使用 jQuery 创建 DOM 元素:

(function($){
    $(function () {
        // create image
        $('<img>')
            // add onLoad handler
            .load(whenImageIsLoadedFunction)
            // set the images 'src'
            .attr('src', 'your/image/source.png');
    });

    function whenImageIsLoadedFunction() {
        // do all your code here.
        $(this).appendTo('#imageContainer');
    }
}(jQuery));
于 2013-10-03T19:05:42.413 回答