| 代碼如下 |
複製代碼 |
|
<script language="JavaScript">
<!--
//圖片按比例縮放
var flag=false;
function DrawImage(ImgD){
var image=new Image();
var iwidth = 160; //定義允許圖片寬度
var iheight = 120; //定義允許圖片高度
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;
}
}
}
//調用:<img src="圖片" onload="javascript:DrawImage(this)">
//-->
</script> |
執行個體二
| 代碼如下 |
複製代碼 |
function resizeimg(ImgD,iwidth,iheight) {
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
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;
}
ImgD.style.cursor= "pointer"; //改變滑鼠指標
ImgD.onclick = function() { window.open(this.src);} //點擊開啟大圖片
if (navigator.userAgent.toLowerCase().indexOf("ie") > -1) { //判斷瀏覽器,如果是IE
ImgD.title = "請使用滑鼠滾輪縮放圖片,點擊圖片可在新視窗開啟";
ImgD.onmousewheel = function img_zoom() //滾輪縮放
{
var zoom = parseInt(this.style.zoom, 10) || 100;
zoom += event.wheelDelta / 12;
if (zoom> 0) this.style.zoom = zoom + "%";
return false;
}
} else { //如果不是IE
ImgD.title = "點擊圖片可在新視窗開啟";
}
}
} |
在需要實現等比縮放的圖片上加上onload語句,圖片裝載時初始化大小。
具體實現代碼如下:
| 代碼如下 |
複製代碼 |
|
<img name="" src="" onload="javascript:resizeimg(this,100,200)"> |