码迷,mamicode.com
首页 > Web开发 > 详细

js控制图片onload 批量设置内容下所有图片的等比例压缩

时间:2016-10-08 01:49:02      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

调用时用  AddImgClickEvent("content",500)   就可以了。

<script type="text/javascript">
function AddImgClickEvent(str,width)
{
var objs = document.getElementById(str).getElementsByTagName("img");
for(var i=0;i<objs.length;i++)
{
objs[i].onload=function()
{
AutoResizeImage(width,0,this);
}
objs[i].style.cursor = "pointer";
}
}

function AutoResizeImage(maxWidth,maxHeight,objImg){
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth ==0 && maxHeight==0){
Ratio = 1;
}else if (maxWidth==0){//
if (hRatio<1) Ratio = hRatio;
}else if (maxHeight==0){
if (wRatio<1) Ratio = wRatio;
}else if (wRatio<1 || hRatio<1){
Ratio = (wRatio<=hRatio?wRatio:hRatio);
}
if (Ratio<1){
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}
</script>

 

 获取 id=content 下的所有图片。。 document.getElementById("content").getElementsByTagName("img"); 

js控制图片onload 批量设置内容下所有图片的等比例压缩

标签:

原文地址:http://www.cnblogs.com/hezhong/p/5937092.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!