2010-06-30 144 views
0

我做了一个jQuery插件,但它不能正常工作。结果不一致。有时候它确实有用,但有时候不行。我认为问题可能是某些变量的加载速度不够快。jQuery插件问题

希望有人能帮忙。提前致谢。

(function($) { 

    $.fn.showhide = function(options) { 

     var defaults = { 
       appear: true, 
       speed: 500 
      }, 
      settings = $.extend({}, defaults, options); 

     this.each(function() { 

      var $this = $(this), 
       elementWidth = $this.width(), 
       elementHeight = $this.height(), 
       newWidth = 0, 
       newHeight = 0, 
       marginX = Math.floor(elementWidth/2), 
       marginY = Math.floor(elementHeight/ 2); 

      if(settings.appear) { 

       console.log(elementWidth + ' ' + elementHeight + ' ' + marginX + ' ' + marginY); 

       $this.css({ width: newWidth + 'px', height: newHeight + 'px', margin: marginY + 'px ' + marginX + 'px' }); 
       $this.animate({ width: elementWidth + 'px', height: elementHeight + 'px', margin: '0px', opacity: 'show' }, settings.speed); 

      } else { 



      } 

     }); 

     return this; 

    } 

})(jQuery); 

编辑

插件用于我的图片上传。当我上传图片时,它应该以一种奇特的方式出现。我使用这个插件上传:valums.com/ajax-upload和onComplete我使用我的插件来显示图像。

+0

你需要定义一下这个jQuery插件是应该做的,以及“工作”的含义。此外,使用此插件的完整HTML示例将会很有帮助。 – 2010-06-30 14:59:51

回答

1

纠正我,如果我错了:

  1. 上传图片的形式,使用AJAX Upload,允许用户上传图片到你的服务器。
  2. AJAX Upload使用新上传的图像的URI调用onComplete回调。
  3. 您创建了一个新的img DOM元素,其中src设置为上传图像的URI。
  4. img DOM元素添加到文档中。
  5. showhideimg元素上被调用。

如果这是正确的,那么它解释了为什么elementWidthelementHeight有时不正确。问题是浏览器需要时间来下载图像,并且elementWidthelementHeight在图像完全加载之前无效。

要解决这个问题,我会尝试在对img一个load回调被注册的src属性设置之前调用showhide

var  $myNewImage = $('<li><img alt="" /></li>'), 
     $i = $myNewImage.children('img'); 

$i.hide(); 
$myNewImage.rightClick(function(e) { 
     // .... 
}); 

$myNewImage.prependTo('.uploadedImages'); 
$('.uploadedImages li').each(function() { 
     var indexNumber = $(this).index(); 
     $(this).children('img').attr('id', 'image_' + indexNumber); 
}); 

$i.load(function() { 
     $i.showhide({ appear: true }); 
}); 
$i.attr('src', 'uploads/thumbs/' + file);