javascript圖片自動縮放和垂直居中處理函數(shù)
更新時間:2008年10月10日 21:59:59 作者:
非常不錯的應用代碼,方便我們處理一些圖片效果
復制代碼 代碼如下:
<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>
注釋:
1、后面的testCss1和testCss2兩個樣式跟testCss是一樣的。只是設置了大小。
2、紅色部分的height和width必須定義,是設置存放img外面的父層容器的高和寬。
3、text-algin:為圖片水平居中
4、display:block,必須設置。否則FF下啟用自動縮放不起作用。
使用方法:
1、是需要在img的父層定義樣式,包含上述注釋里面提到的東西;
2、是img加上
onload="autoSizeImg(this.parentNode,5,5,true)"
參數(shù)說明:
參數(shù)Contents一般采用this.parentNode,即使img的父容易
參數(shù)offsetWidth,offsetHeight分別是寬和高度居中的修正值。
參數(shù)vlmiddle設置為true則是垂直居中
[Ctrl+A 全選 注:引入外部Js需再刷新一下頁面才能執(zhí)行]
相關文章
JavaScript判斷圖片是否能夠加載,失敗則替換默認圖片
JavaScript智能判斷圖片是否能夠正確加載,若加載失敗則用默認圖片替換,這是個比較實用的功能,不少網站都可見到這種功能.2010-10-10
javascript 火狐(firefox)不顯示本地圖片問題解決
在Firefox一直不能用js做出圖片預覽的效果,下面這個即可解決,用替換的方法實現(xiàn)firefox支持得的路徑格式2008-07-07
javascript預覽上傳圖片發(fā)現(xiàn)的問題的解決方法
前段時間做一個行業(yè)站點,其中商鋪有一塊功能是商鋪設置功能,要求是進行版式,企業(yè)名稱,企業(yè)頭部LOGO,企業(yè)頭部背景進行自定義設置。2010-11-11
JS圖片瀏覽組件PhotoLook的公開屬性方法介紹和進階實例代碼
這次接著來介紹PhotoLook(前文介紹的組件)現(xiàn)在可供使用的屬性和方法,接著展示一個叫前文不一樣的例子2010-11-11

