欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js 图片等比例缩放代码

程序员文章站 2022-04-12 11:19:00
复制代码 代码如下: var scaleimage = function(o, w, h){ var img = new image(); img.src = o.src;...
复制代码 代码如下:

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;
}
}
}

html
复制代码 代码如下:

<div>
<p><img src="../comment/img/max.jpg" onload="scaleimage(this,300,300)" alt="pic" /></p>
<p><img src="../comment/img/2.jpg" onload="scaleimage(this,300,300)" /></p>
<p><img src="../comment/img/3.jpg" onload="scaleimage(this,300,300)" /></p>
<p><img src="../comment/img/4.jpg" onload="scaleimage(this,300,300)" /></p>
</div>