2010-06-30 140 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);