[轉]圖片自動縮放 js圖片縮放

 

<script type="text/javascript"></script>

轉自:http://hi.baidu.com/crystalhx/blog/item/deba9b2320274340ac34de09.html

圖片自動縮放 js圖片縮放
2008-03-27 10:48

 

圖片自動縮放 js圖片縮放

對於不指定大小的圖片默認是以原大小顯示,所以在不指定大小的圖片上用onload事件觸發腳本代碼,在代碼中判斷圖片的尺寸,如果超過指定值,將自動設置爲允許的最大值。

具體步驟:
方法一:在圖片加載完畢後用onload句柄觸發執行腳本,重設圖片的寬度爲圖片寬度和300兩者的最小值。
代碼示例: <img src="demo.gif" οnlοad="if(this.width>300)this.width=300">
或者
<img src="demo.gif" οnlοad="this.width=Math.min(this.width,300)">

方法二:按比例縮小。只需要把js加在head之間,再在body處加入οnlοad="ResizeImages();"代碼。
<script language="JavaScript">
<!--
function ResizeImages()
{
var myimg,oldwidth;
var maxwidth=180; //縮放係數
for(i=0;i <document.images.length;i++){
myimg = document.images[i];
if(myimg.width > maxwidth)
{
oldwidth = myimg.width;
myimg.width = maxwidth;
myimg.height = myimg.height * (maxwidth/oldwidth);
}
}
}
//-->
</script>

<script language="JavaScript">
<!--
//圖片按比例縮放
var flag=false;
function DrawImage(ImgD,iwidth,iheight){
//參數(圖片,允許的寬度,允許的高度)
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>= iwidth/iheight){
if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"×"+image.height;
}
}
}
//-->
</script>

調用:<img src="images/toplogo.gif" οnlοad="javascript:DrawImage(this,100,100)">

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