Javascript ~ auto resize img by fixed frame

這是我自己寫的auto Resize程式XD

雖然之前PHP就寫過一個了.........

只要在img裡加個onload跑這函示就可~

有針對兩種情況resize~~~~~~

一種是高或寬超過框

一種是高跟寬~~都小於框


HTML
------------------------------------------------------------------------------------------
<img src="ggyy.jpg" height="200" width="200" onload="setImgSize(this)" >


Javascript
------------------------------------------------------------------------------------------
function setImgSize(e)
{
var newImg = new Image();
newImg.src = e.src;
var height = newImg.height;
var width = newImg.width;

var frameHeight = 200;
var frameWidth = 200;
//set the frame size

var ratio = 1;

if(height > width)
{
ratio = height / frameHeight;
}
else
{
ratio = width / frameWidth;
}

if(frameHeight > height && frameWidth > width)
{
e.height = height;
e.width = width;
}
else
{
e.height = parseInt(height / ratio);
e.width = parseInt(width / ratio);
}
}

沒有留言: