vue版本:
jQuery版本:
// 按比例缩放图片并居中 (resizeType: cover 撑满整个容器,多出部分截掉 / contain 长或宽跟容器一样)
//scaling 是否缩放、true/false
//panelWidth父元素的宽度
//panelHeight父元素的高度
//resizeType缩放的方式cover/contain;
jQuery.fn.ResizeImages = function (scaling, panelWidth, panelHeight, resizeType) {
var loadingImg = 'http://css.XXXXXXXX.com/mobile/img/loading.gif';//图片加载gif
var resizeType = resizeType || 'cover';
return this.each(function (i, value) {
var t = $(this);
var src = $(this).attr('src'), alt=$(this).attr("alt"), img = new Image();
img.src = src;
var autoScaling = function (imgWidth,imgHeight,panelWidth,panelHeight) {
if (scaling) {
if (imgWidth > 0 && imgHeight > 0) {
if (resizeType === 'cover') {
// 默认 cover 方式,处理后的宽或高超过容器的宽高,用margin负值使之上下或左右居中
// 如果图片比容器扁
if (imgWidth / imgHeight >= panelWidth / panelHeight) {
var toWidth = imgWidth * (panelHeight / imgHeight);
t.width(toWidth);
t.height(panelHeight);//等比缩放,保持清晰度
t.css({ marginLeft: -((toWidth - panelWidth) / 2) });
}
// 如果图片比容器瘦
else {
var toHeight = imgHeight * (panelWidth / imgWidth);
t.width(panelWidth);
t.height(toHeight);//等比缩放,保持清晰度
t.css({ marginTop: -((toHeight - panelHeight) / 2) });
}
}else if (resizeType === 'contain') {
// contain方式,处理后的宽或高不足容器的宽高,用margin正值使之上下或左右居中
if (imgWidth / imgHeight >= panelWidth / panelHeight) {
var toHeight = imgHeight * (panelWidth / imgWidth);
t.width(panelWidth);
t.height(toHeight);
t.css({ marginTop: (panelHeight - toHeight) / 2 });
}else {
var toWidth = imgWidth * (panelHeight / imgHeight);
t.width(toWidth);
t.height(panelHeight);
//t.css({ marginLeft: (panelWidth - toWidth) / 2 }); // 容器已居中
}
}
t.removeClass("resize-error").addClass("resized");
}
}
};
// 处理FF下会自动读取缓存图片
if (img.complete && img.width>0) {
autoScaling(img.width,img.height,panelWidth,panelHeight);
return;
}
t.css({'background':'url('+loadingImg+') no-repeat center center','background-size':'16px 16px','width':panelWidth,'height':panelHeight})
$(img).load(function () {
t.attr({'src': src,'alt':alt}).css('background',"none");
autoScaling(this.width,this.height,panelWidth,panelHeight);
}).error(function () {
if(img.complete && this.width>0){
t.attr({'src': src,'alt':alt}).css('background',"none");
if(!$(this).hasClass("resized")){
autoScaling(this.width,this.height,panelWidth,panelHeight);
}
}else{
t.css('background',"none").removeClass("resized").addClass("resize-error");
}
});
});
};