开发者

Problems with jQuery Plugin

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:

  1. An image upload form, using AJAX Upload, allows users to upload an image onto your server.
  2. AJAX Upload calls an onComplete callback with the URI of the newly-uploaded image.
  3. You create a new img DOM element with src set to the URI of the uploaded image.
  4. The img DOM element is added to the document.
  5. showhide is called on the img element.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜