【问题标题】:image onload event triggering before its image fully loaded?在图像完全加载之前触发图像加载事件?
【发布时间】:2010-11-02 13:05:09
【问题描述】:

我正在使用 Jcrop jquery 插件,并在 onload 事件上触发 initJcropBox() 函数。

但此功能在图像完全加载之前被触发。这导致了问题。例如显示不正确的 jcropbox 大小或根本不显示 jcropbox。

当我放置一条线时,它工作正常。但不是解决方案。 setTimeout('initJcropBox()',2000);

图像在浏览器中完全加载/渲染后如何触发initJcropbox()函数?

  var api;

     function initJcropBox(){
      api = $.Jcrop('#cropbox',{
          bgColor: 'black',
          bgOpacity: .7,
          onSelect: updateCoords,
          onChange: updateCoords,
          boxWidth: 400
      });
        api.animateTo([0,0,$('#cropbox').width(),$('#cropbox').height()]);
    }     

    function insertImage(name) {
        var img = new Image();
        img.onload = initJcropBox;
        img.src = name;
        img.id = 'cropbox';

        return img;
    }

$('td.imageFile').live('click', function(e){
    fileWithPath = "uploads/original/" + $(this).text();
    $('#cropbox').remove();
    $("#cropcontainer").empty().html(insertImage(fileWithPath));
});

【问题讨论】:

    标签: jquery onload onload-event jcrop


    【解决方案1】:

    google一下,我自己解决这个问题。这是可行的解决方案

    function insertImage(name) {
    
      var img = new Image();
      img.id = 'cropbox';
      img.src = name;
    
      if(img.complete) setTimeout('initJcropBox()', 500);   
      else onload= initJcropBox;  
    
      return img;
     }
    

    【讨论】:

      【解决方案2】:

      尝试用它替换您的 insertImage(name) 函数。这应该会触发图像上的加载事件,直到它真正加载为止。

      function insertImage(name) {
          var img = $('<img id="cropbox" />');
          img.load(function(){ 
                      if (! this.complete) {
                        return false;
                        $(this).load();
                      }
      
                      else if (typeof this.naturalWidth != 'undefined' && this.naturalWidth == 0) {
                        return false;
                        $(this).load();
                      }
                      else
                        initJcropBox();
                   })
              .attr('src',name);
          return img;
      }
      

      我没有测试过,所以让我知道它是否值得。

      【讨论】:

        【解决方案3】:

        前段时间我遇到了类似的问题。使用 load() 加载图像并触发回调函数。 Here 更多详情。

        【讨论】:

          猜你喜欢
          • 2012-03-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多