query预加载等比缩放图片并居中显示



    <script type="text/javascript">
        /*
        scaling 是否等比例自动缩放
        width 图片最大高
        height 图片最大宽
        loadpic 加载过程中显示的图片路径
        */
        jQuery.fn.LoadImage = function (scaling, width, height, loadpic) {
            if (loadpic == null) {
                loadpic = "../../Images/loading.gif";
            }
            return this.each(function () {
                var t = $(this);
                var src = $(this).attr("src")
                var img = new Image();
                img.src = src;
                var autoScaling = function () {
                    if (scaling) {
                        if (img.width > 0 && img.height > 0) {
                            if (img.width / img.height >= width / height) {
                                if (img.width > width) {
                                    t.width(width);
                                    t.height((img.height * width) / img.width);
                                } else {
                                    t.width(img.width);
                                    t.height(img.height);
                                }
                            } else {
                                if (img.height > height) {
                                    t.height(height);
                                    t.width((img.width * height) / img.height);
                                } else {
                                    t.width(img.width);
                                    t.height(img.height);
                                }
                            }
                        }
                        //在父容器中居中显示
                        t.css("margin-left", ($("#" + t.context.parentNode.id).width() - t.width()) * 0.5 + "px");
                        t.css("margin-top", ($("#" + t.context.parentNode.id).height() - t.height()) * 0.5 + "px");
                    }
                }
                //处理ff下会自动读取缓存图片
                if (img.complete) {
                    autoScaling();
                    return;
                }
                $(this).attr("src", "");
                var loading = $("<img alt=\"加载中\" title=\"图片加载中\" src=\"" + loadpic + "\" />");

                t.hide();
                t.after(loading);
                $(img).load(function () {
                    autoScaling();
                    loading.remove();
                    t.attr("src", this.src);
                    t.show();
                });
            });
        }

        //调用的例子
        $("div[id^='divProduct'] img[id^='imgProduct']").LoadImage(true, 396, 300);
        $("div[id^='divPhoto'] img").LoadImage(true, 200, 240);
</script>

posted on 2013-10-10 22:10  丰云  阅读(101)  评论(0编辑  收藏  举报

导航