当图片在页面显示时,如果宽度大于高度且大于显示区域宽度那么以宽度为准等比缩放;如果高度大于宽度且大于显示区域高度那么以高度为准;若大者都小于显示区域对应尺寸时,不用缩放只用居中显示;要实现这个功能的话可以上传的时候用程序对图片裁切,而这里要将的是用js在web端实现此功能,其实很简单,js代码如下:
// JavaScript Document
function changeImgSize(target){
//外框宽
maxWidth = parseInt($(target).parent().css("width").replace(/px/,""));
//外框高
maxHeight = parseInt($(target).parent().css("height").replace(/px/,""));
//图片宽
imgWidth = target.offsetWidth;
//图片高
imgHeight = target.offsetHeight;
var viewWidth,viewHeight;
if (imgWidth / maxWidth > imgHeight / maxHeight){
if (imgWidth > maxWidth){
viewWidth = maxWidth;
viewHeight = maxWidth / imgWidth * imgHeight;
$(target).css("margin-top",(maxHeight - viewHeight) / 2);
}else{
viewWidth = imgWidth;
viewHeight = imgHeight;
$(target).css("margin-top",(maxHeight - viewHeight) / 2);
$(target).css("margin-left",(maxWidth - viewWidth) / 2);
}
}else if (imgWidth / maxWidth < imgHeight / maxHeight){
if (imgHeight > maxHeight){
viewHeight = maxHeight;
viewWidth = maxHeight / imgHeight * imgWidth;
$(target).css("margin-left",(maxWidth - viewWidth) / 2);
}else{
viewWidth = imgWidth;
viewHeight = imgHeight;
$(target).css("margin-top",(maxHeight - viewHeight) / 2);
$(target).css("margin-left",(maxWidth - viewWidth) / 2);
}
}
$(target).css("width",viewWidth);
$(target).css("height",viewHeight);
}
(function($) {
$.fn.extend({
reSize: function() {
return this.each(function () {
changeImgSize(this);
});
}
});
})(jQuery);
页面图片显示代码如下:
<div class="imgdiv"><img src="images/index_b.jpg" ></div>
对应的样式如下:
.piclist .imgdiv {
width: 122px;
height: 92px;
float: left;
overflow: hidden;
}