function resizeImg(tar,w,h){
var img = new Image();
img.src = tar.src;
tar.style.visibility = 'hidden';
if(img.width>0 && img.height>0){
if(img.width<img.height){
if(img.width > w){
tar.height = h;
tar.width = (img.width*h)/img.height;
}else{
if(img.height < h){
tar.width = img.width;
}else{
tar.height = h;
}
}
}else if(img.height<img.width){
if(img.height > h){
tar.height = (img.height*w)/img.width;
tar.width = w;
}else{
if(img.width < w){
tar.height = img.height;
}else{
tar.width = w;
}
}
}
tar.style.marginTop = -(tar.height - h)/2+"px";
tar.style.marginLeft = -(tar.width - w)/2+"px";
tar.style.visibility = 'visible';
}
}
/*
resizeImgCut 顯示區域只顯示圖片中間部分並且居中
*/
function resizeImgCut(tar,w,h){
var img = new Image();
img.src = tar.src;
tar.style.visibility = 'hidden';
if(img.width>0 && img.height>0){
if(img.width<img.height){
if(img.width > w){
tar.width = w;
tar.height = (img.height*w)/img.width;
}else{
if(img.height < h){
tar.width = img.width;
}else{
tar.height = h;
}
}
}else if(img.height<img.width){
if(img.height > h){
tar.height = h;
tar.width = (img.width*h)/img.height;
}else{
if(img.width < w){
tar.height = img.height;
}else{
tar.width = w;
}
}
}else{
//tar.width = w;
//tar.height = h;
}
tar.style.marginTop = -(tar.height - h)/2+"px";
tar.style.marginLeft = -(tar.width - w)/2+"px";
tar.style.visibility = 'visible';
}
}
resizeImg方法對應以下圖片,如果圖片大於顯示區域,顯示區域顯示圖片全部並居中顯示,如果圖片小於顯示區域,則保持原來的寬高,居中顯示。
<img src="demo.jpg" onload="resizeImg(400,400,this)" />