javascript图片自动缩放-判断图片大小
广告:
<img src="aa.jpg" onload="javascript:if(this.width>200){this.width=this.width*0.6;this.height=this.height*0.6;}">
对于img标签 onload不能通过w3c认证有以下解决方法:
function imgfixlen()
{
obj=document.getElementsByTagName("img");
for(i=0;i<obj.length;i++)
{
if(obj[i].className=="futu")
{
if(obj[i].width>400) obj[i].width=400;
if(obj[i].height>200) obj[i].height=200;
}
}
}
Html代码:
<body onload="imgfixlen()">
Img标记:
<img src="图片URL" alt="图片说明" class="futu" />
或:
全局,即当前页面中的所有图片:
function loadImgs()
{
var imgs = document.images;
var max_width = 500;
for (var i=0; i<imgs.length; i++)
{
var w = imgs[i].width;
var h = imgs[i].height;
if (w > max_width)
{
imgs[i].width = max_width;
imgs[i].height = h*max_width/w;
}
}
}
window.onload = loadImgs;
单个图片,由图片唯一ID区分
function loadImgs()
{
var imgs = document.getElementById("imgId");
var max_width = 500;
var w = imgs.width;
var h = imgs.height;
if (w > max_width)
{
imgs.width = max_width;
imgs.height = h*max_width/w;
}
}
window.onload = loadImgs;
多个图片,一类图片数组,即所有ID名都为 imgId的图片
function loadImgs()
{
var imgs = document.getElementsByName("imgId");
var max_width = 120;
for (i=0;i<imgs.length;i++){
var w = imgs[i].width;
var h = imgs[i].height;
if (w > max_width)
{
imgs[i].width = max_width;
imgs[i].height = h*max_width/w;
}
}
}
window.onload = loadImgs;
或
function loadimghao() //class="imgload-200-180" 传入宽高
{
var widthtemp=100; //函数内部临时变量,初始值
var loadwidthtemp=100; // 传入宽,初始值
var loadheighttemp=100; // 传入高,初始值
var imghaohaibotemp= new Array; //定义数组;
obj=document.getElementsByTagName("img");
for(i=0;i<obj.length;i++)
{
if(obj[i].className.substring(0,7)=="imgload")
{
imghaohaibotemp=obj[i].className.split("-");
if (imghaohaibotemp.length==3)
{
loadwidthtemp=imghaohaibotemp[1];
loadheighttemp=imghaohaibotemp[2];
if(obj[i].height>loadheighttemp)
{
widthtemp=obj[i].width*loadheighttemp/obj[i].height;
obj[i].height=loadheighttemp;
if (widthtemp>loadwidthtemp)
obj[i].width=loadwidthtemp;
else
obj[i].width=widthtemp;
}
}
}
}
}
window.onload = loadimghao;
广告: