JS圖片自適應顯示

   在上一家公司的時候,由於項目的關係就一直想寫一個這樣的類出來用的了,無奈各種原因,擱置了。
   剛好前段時間公司有個博客的項目,就心血來潮,搞了一個出來。在製作相冊頁面的時候很糾結。用戶上傳的照片的格式會有很多種,那麼怎麼才能讓所有不同尺寸的圖片都用相同的尺寸來顯示而不影響排版呢?
    分享兩個自己寫的方法
    
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';
		}
}



resizeImgCut方法對應以下圖片,如果圖片大於顯示區域,顯示區域只顯示圖片中間部分,如果圖片小於顯示區域,則保持原來的寬高,居中顯示。


resizeImg方法對應以下圖片,如果圖片大於顯示區域,顯示區域顯示圖片全部並居中顯示,如果圖片小於顯示區域,則保持原來的寬高,居中顯示。


使用方法:

<img src="demo.jpg" onload="resizeImg(400,400,this)" />


歡迎拍磚。。
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章