JS按比例缩放图片

来源:互联网 发布:c语言中!x是什么意思 编辑:程序博客网 时间:2024/05/03 22:08

 在网页设计或编程中如何以最方便的方法来处理图片的宽高,以达到最佳的显示效果,这个问题相信很多网页制作人员都遇到过,最麻烦最费时间的做法是用制图软件Photoshop等来一张张处理,这种方法如果处理一两张还好点,多了真是麻烦;最快的做法是直接给图片固定一个宽高,这样做的缺点就是影响页面的美观,而大多数的做法是使用JS来控制图片的显示尺寸在一定的范围内,不会比例失调,保证了图片不会变形,相信这种方法是最合适的。

下面这段脚本在IE、FIREFOX、OPERA、NETSCAPE测试都适用(by@蛐蛐):

function SetSize(obj, width, height)
{
myImage = new Image();
myImage.src = obj.src;
if (myImage.width>0 && myImage.height>0)
{
var rate = 1;
if (myImage.width>width || myImage.height>height)
{
if (width/myImage.width<height/myImage.height)
{
rate = width/myImage.width;
}
else
{
rate = height/myImage.height;
}
}
if (window.navigator.appName == "Microsoft Internet Explorer")
{
obj.style.zoom = rate;
}
else
{
obj.width = myImage.width*rate;
obj.height = myImage.height*rate;
}
}
}

 

用法:

<img src="img/offer/41936519.jpg" border="0" style="zoom: 0.1" onload="SetSize(this, 80, 60)"/>

转自:http://mawendong.cn/article.asp?id=579



自己测试,可以不用加上style="zoom: 0.1"
<img alt="" src="/upload/<%=bigpic %>" onload="SetSize(this, 350, 500)" />


原创粉丝点击