完整代码如下:
复制代码 代码示例:
<script language="
javascript">
var scaleImage = function(o, w, h){
var img = new Image();
img.src = o.src;
if(img.width >0 && img.height>0)
{
if(img.width/img.height >= w/h)
{
if(img.width > w)
{
o.width = w;
o.height = (img.height*w) / img.width;
}
else
{
o.width = img.width;
o.height = img.height;
}
o.alt = img.width + "x" + img.height;
}
else
{
if(img.height > h)
{
o.height = h;
o.width = (img.width * h) / img.height;
}
else
{
o.width = img.width;
o.height = img.height;
}
o.alt = img.width + "x" + img.height;
}
}
}
</script>
相比之前介绍过的图片按比例缩放的js实现代码,以上脚本更显简洁,层次清晰,易于学习。
页面调用:
复制代码 代码示例:
<div>
<p><img src="../files/img/max.jpg" onload="scaleImage(this,300,300)" alt="pic" /></p>
<p><img src="../files/img/2.jpg" onload="scaleImage(this,300,300)" /></p>
<p><img src="../files/img/3.jpg" onload="scaleImage(this,300,300)" /></p>
<p><img src="../files/img/4.jpg" onload="scaleImage(this,300,300)" /></p>
</div>