图像onload事件在其图像完全加载之前触发?

时间:2010-11-02 13:05:10

标签: jquery onload onload-event jcrop

我正在使用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));
});

3 个答案:

答案 0 :(得分:1)

只是谷歌,我自己解决这个问题。这是工作解决方案

function insertImage(name) {

  var img = new Image();
  img.id = 'cropbox';
  img.src = name;

  if(img.complete) setTimeout('initJcropBox()', 500);   
  else onload= initJcropBox;  

  return img;
 }

答案 1 :(得分:0)

尝试用此替换您的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;
}

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

答案 2 :(得分:-1)

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

相关问题