js等比例经缩小图片并居中显示
在做产品展示的时候经常要求产品图片等比例缩小并居中显示
来看看根据以前的一个函数进化而来的更完善的js函数:
[js]
//等比例缩小图片
function clacImgZoomParam( maxWidth, maxHeight, width, height ){
var param = {top:0, left:0, width:width, height:height};
if( width>maxWidth || height>maxHeight )
{
rateWidth = width / maxWidth;
rateHeight = height / maxHeight;
if( rateWidth > rateHeight )
{
param.width = maxWidth;
param.height = Math.round(height / rateWidth);
}else
{
param.width = Math.round(width / rateHeight);
param.height = maxHeight;
}
}
param.left = Math.round((maxWidth - param.width) / 2);
param.top = Math.round((maxHeight - param.height) / 2);
return param;
}
[/js]
然后这样调用
[js]
//图片所在元素的ID
var img = document.getElementById('img');
img.onload = function(){
var rect = clacImgZoomParam(100, 100, img.offsetWidth, img.offsetHeight);
img.width = rect.width;
img.height = rect.height;
img.style.marginLeft = rect.left+'px';
img.style.marginTop = rect.top+'px';
}
[/js]
经常用到的朋友可以记录转载过去!以并以后查看!