用JS控制图片大小按比例放缩或扩大图片

第一个: 按比例扩大或缩小图片

<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script language="JavaScript">
<!--
var flag=false;
function DrawImage(ImgD){
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
flag=true;
if(image.width/image.height>= 164/112){
if(image.width>164){
ImgD.width=164;
ImgD.height=(image.height*164)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"x"+image.height;
}
else{
if(image.height>112){
ImgD.height=112;
ImgD.width=(image.width*112)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
ImgD.alt=image.width+"x"+image.height;
}
}
}
//-->
</script>
</HEAD>

<BODY>

<a href="./img.jpg" target="_blank"><img src="./img.jpg" border="0" width="164" height="112" οnlοad="javascript:DrawImage(this);"></a>
</BODY>
</HTML>

第二个: 控制图片的宽度和高度不得超过某个值

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/...
<html xmlns="http://www.w3.org/1999/xht...
<head>
<title>图 片大小控制</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
</head>
<body>
此JS脚本实现图片大小自动适应,如果文中有图片宽度超过300,就自动缩小。
在IE、FF里通过测试,但在OPERA需要刷新一次 才会自动缩小,
<table id="abc">
<tr>
<td><img src="xxx" />
</tr>
</table>
<script>
var abc=document.getElementById("abc");
var imgs=abc.getElementsByTagName("img");
for (var i=0,g;g=imgs[i];i++)
g.οnlοad=function(){if (this.width>300){this.width=300}else{if (this.height>300)this.height=300}}
</script>
</body>
</html>

 

我在用火车采集器采集的文章图片大小经常会撑破文章内容的div,所以要控制图片大小,在网上找到很多种,觉得还是这两个比较好一些,所以贴出来和大家分享一下。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值