javascript圖片自動(dòng)縮放和垂直居中處理函數(shù)
更新時(shí)間:2008年10月10日 21:59:59 作者:
非常不錯(cuò)的應(yīng)用代碼,方便我們處理一些圖片效果
復(fù)制代碼 代碼如下:
<html>
<head>
<title>Untitled</title>
<style type="text/css">
.testCss{width:200px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss1{width:300px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss2{width:400px;height:300px;border:1px red solid;text-align:center;display:block;}
</style>
<script type="text/javascript">
function autoSizeImg(Contents,offsetWidth,offsetHeight,vlmiddle){
var o=Contents.getElementsByTagName("IMG");
var cwidth= window.getComputedStyle?window.getComputedStyle(Contents,null).width:Contents.currentStyle["width"];
var cheight=window.getComputedStyle?window.getComputedStyle(Contents,null).height:Contents.currentStyle["height"];
var ncwidth=parseInt(cwidth);
var ncheight=parseInt(cheight);
for(var i=0;i<o.length;i++){
var img=o[i];
var iw=img.width;
var ih=img.height;
if(img.width>ncwidth){
var nw=ncwidth-offsetWidth;
img.width=nw
img.height=(nw*ih)/iw;
}else if(img.width<ncwidth&&img.height>ncheight){
var nh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(img.height>ncheight&&img.width<ncwidth){
var hh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(vlmiddle)img.style.marginTop=((ncheight-img.height)/2)+"px";
}
}
</script>
</head>
<body>
<div class="testCss">
<img src="http://img.jbzj.com/file_images/sucai/111131524.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div class="testCss1">
<img src="/upload/20081010215957304.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div> </div>
<div class="testCss2">
<img src="/upload/20081010215958874.gif" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
</body>
</html>
注釋?zhuān)?/STRONG>
1、后面的testCss1和testCss2兩個(gè)樣式跟testCss是一樣的。只是設(shè)置了大小。
2、紅色部分的height和width必須定義,是設(shè)置存放img外面的父層容器的高和寬。
3、text-algin:為圖片水平居中
4、display:block,必須設(shè)置。否則FF下啟用自動(dòng)縮放不起作用。
使用方法:
1、是需要在img的父層定義樣式,包含上述注釋里面提到的東西;
2、是img加上
onload="autoSizeImg(this.parentNode,5,5,true)"
參數(shù)說(shuō)明:
參數(shù)Contents一般采用this.parentNode,即使img的父容易
參數(shù)offsetWidth,offsetHeight分別是寬和高度居中的修正值。
參數(shù)vlmiddle設(shè)置為true則是垂直居中
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁(yè)面才能執(zhí)行]
相關(guān)文章
純CSS實(shí)現(xiàn)的當(dāng)鼠標(biāo)移上圖片添加陰影效果代碼
這個(gè)效果挺實(shí)用,當(dāng)把鼠標(biāo)放到一幅靜止的圖片上,圖片的四周邊框會(huì)出現(xiàn)陰影,具有立體感的效果,代碼是第二次修正,能適應(yīng)大小不同的圖片,值得大家嘗試一用哦。2009-12-12JS實(shí)現(xiàn)全景圖效果360度旋轉(zhuǎn)
JS實(shí)現(xiàn)全景圖效果360度旋轉(zhuǎn)...2007-01-01圖片展示效果 鼠標(biāo)經(jīng)過(guò)變大圖,支持FF
圖片展示效果,鼠標(biāo)經(jīng)過(guò)變大圖,支持FF 類(lèi)似FLASH一樣漂亮2009-08-08鼠標(biāo)移動(dòng)到一張圖片時(shí)變?yōu)榱硪粡垐D片
鼠標(biāo)移動(dòng)到一張圖片時(shí)變?yōu)榱硪粡垐D片...2006-12-12