您的位置:首页 > 产品设计 > UI/UE

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

2013-10-10 22:10 330 查看


<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: