画像の自動スケーリングを制限範囲で実現

3317 ワード

一)方法1

<style type="text/css">
.Image-max-width {   

    max-width:200px;height:auto;cursor:pointer;   

    border:1px dashed #4E6973;padding: 3px;   

    zoom:expression( function(elm) {   

        if (elm.width>2000) {   

            var oldVW = elm.width; elm.width=200;   

            elm.height = elm.height*(200 /oldVW);  

        }  

        elm.style.zoom = '1';  

    }(this)); 

}
.Image-max-height{   

    max-height:200px;width:auto;cursor:pointer;   

    border:1px dashed #4E6973;padding: 3px;   

    zoom:expression( function(elm) {   

        if (elm.height>2000) {   

            var oldVH = elm.height; elm.height=200;   

            elm.width = elm.width*(200 /oldVH);  

        }  

        elm.style.zoom = '1';  

    }(this)); 

}
</style>


<script type="text/javascript">
	function Wa_SetImgAutoSize(img) {
	    //var img=document.all.img1;// 
	    var MaxWidth = 200; // 
	    var MaxHeight = 200; // 
	    var HeightRatio = img.offsetHeight / MaxHeight; // 
	    var WidthRatio = img.offsetWidth / MaxWidth; // 
	  
	    if (HeightRatio > WidthRatio) {
		    alert("t");
	        $(img).addClass("Image-max-height");
	    } 
	    if (HeightRatio < WidthRatio) {
	    	 alert("tt");
	        $(img).addClass("Image-max-width");
	    } 
	}
</script>



呼び出し方法:

<div align=center style="width:200px;height:200px;" ><img  src =" " onload='Wa_SetImgAutoSize(this);'/></div>

参照先:
http://www.cnblogs.com/MaxIE/archive/2008/03/27/1123881.html
二)方法2

<script type="text/javascript">
	function Wa_SetImgAutoSize(img) {
	    //var img=document.all.img1;// 
	    var MaxWidth = 200; // 
	    var MaxHeight = 200; // 
	    var HeightWidth = img.offsetHeight / img.offsetWidth; // 
	    var WidthHeight = img.offsetWidth / img.offsetHeight; // 
	    if (img.offsetWidth > MaxWidth) {
	        $(img).css("width", MaxWidth);
	        $(img).css("height", MaxWidth * HeightWidth);
	    } 
	    if (img.offsetHeight > MaxHeight) {
	        $(img).css("height", MaxHeight);
	        $(img).css("width", MaxHeight * WidthHeight);
	    } 
	}
</script>

呼び出し方法:

<div align=center style="width:200px;height:200px;" ><img  src =" " onload='Wa_SetImgAutoSize(this);'/></div>

参照先:
http://www.codefans.net/jscss/code/513.shtml