﻿//**********************图片按比例居中加载插件************************
//作者：陈毅荣(2009-07-01)
//Email：iddqd5376@163.com
//版本：1.0

//说明：图片按比例居中加载插件

//参数设置：
//width                     存放图片固定大小容器的宽
//height                    存放图片固定大小容器的高
//**********************图片按比例居中加载插件*************************
(function($) {
    jQuery.fn.extend({
        loadImg: function(opts) {
            opts = jQuery.extend({
                width: 0,
                height: 0,
                loadpic: "",
                callback: function() { return false; }
            }, opts || {});
            return this.each(function() {
                var _self = this;
                var _this = $(this);
                var src = $(this).attr("src");
                var img = new Image();
                img.src = src;

                var autoScaling = function() {
                    if (img.width > 0 && img.height > 0) {
                        var rate = (opts.width / img.width < opts.height / img.height) ? opts.width / img.width : opts.height / img.height;
                        if (rate <= 1) {
                            _this.width(img.width * rate);
                            _this.height(img.height * rate);
                        } else {
                            _this.width(img.width);
                            _this.height(img.height);
                        }
                        var left = (opts.width - _this.width()) * 0.5;
                        var top = (opts.height - _this.height()) * 0.5;
                        _this.css({ "margin-left": left, "margin-top": top });
                    }
                }
                if (img.complete) {
                    autoScaling();
                    return;
                }
                _this.hide();

                if (opts.loadpic != "") {

                    var loading = $("<img alt=\"加载中...\" title=\"图片加载中...\" style=\"border:0;\" src=\"" + opts.loadpic + "\" />");
                    _this.after(loading);
                    loading.css({ "margin-left": (opts.width - loading.width()) * 0.5, "margin-top": (opts.height - loading.height()) * 0.5 });
                }
                $(img).load(function() {
                    autoScaling();
                    if (opts.loadpic != "") {
                        loading.remove();
                    }
                    _this.attr("src", this.src);
                    _this.show();
                });
            });
        }
    });
})(jQuery);
