I have made a jQuery plugin, but it doesn't work properly. The results are not consistent. Sometimes it does work, but sometimes not. I think the problem may be that some of the variables don't load fast enough.
Hope someone can help. Thanks in advance.
(function($) {
$.fn.showhide = function(options) {
var defaults = {
appea开发者_运维知识库r: 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);
EDIT
The plugin is used for my image uploader. When I upload an image it should appear in a fancy way. I use this plugin for uploading: valums.com/ajax-upload and onComplete I use my plugin to show the image.
Correct me if I'm wrong:
- An image upload form, using AJAX Upload, allows users to upload an image onto your server.
- AJAX Upload calls an
onCompletecallback with the URI of the newly-uploaded image. - You create a new
imgDOM element withsrcset to the URI of the uploaded image. - The
imgDOM element is added to the document. showhideis called on theimgelement.
If this is correct, then it explains why elementWidth and elementHeight are sometimes not correct. The problem is that the browser needs time to download the image, and elementWidth and elementHeight are not valid until the image has been fully loaded.
To fix this problem, I would try calling showhide in a load callback on the img that is registered before the src attribute is set:
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);
加载中,请稍侯......
精彩评论