在写h5页面的时候,经常会需要将图片自适应大小,一般都是用等比例的缩放,这就有个问题,当上传的图片不是一个规格时就会出现展示图片不完美。
为了解决这个问题,我们可以通过js去获取图片的大小,然后在根据屏幕计算图片展示的实际大小,在通过之间的比例缩小图片,并且是不破坏图片质量的情况下居中展示图片。
效果如下:
通过效果图可以看出,长图的展示效果,并不是等比例的收缩,而是在一定比例的情况下,展示图片内容的一部分。这样即达到了展示图片的效果,又解决了图片展示破坏美观的难点。
那么,下面来看是怎么通过js获取屏幕大小设置图片自适应的。
html代码:
js代码:
var imgContainerHeight ;
function ImgPosInitMob(obj, type) {
// 初始化父级元素的宽高
imgContainerHeight = ($(window).width() - 10) / 2; // 两张图情况 边距10px
$(obj).parent().height(imgContainerHeight);
$(obj).parent().width(imgContainerHeight);
// 设置img图片的宽高
var img = $(obj);
if (!type) type = 1;
if (typeof obj.naturalWidth != "undefined") {
var realWidth = obj.naturalWidth;
var realHeight = obj.naturalHeight;
var standwidth = $(img.parent()).width();
var standheight = $(img.parent()).height();
var tempwidth = 0,tempheight = 0;
var ratew = standwidth / realWidth,rateh = standheight / realHeight;
if (type == 1) {
if (rateh >= ratew) {
tempheight = standheight;
tempwidth = realWidth * rateh;
} else {
tempwidth = standwidth;
tempheight = realHeight * ratew;
}
} else if (type == 2) {
if (rateh <= ratew) {
tempheight = standheight;
tempwidth = realWidth * rateh;
} else {
tempwidth = standwidth;
tempheight = realHeight * ratew;
}
}
img.height(tempheight);
img.width(tempwidth);
img.css("margin-top", -(tempheight - standheight) / 2);
img.css("margin-left", -(tempwidth - standwidth) / 2);
}
}