最近做一个图片的自动缩小效果,发现一直用的js,竟然在firefox下无法正常啊,导致页面变形.所以自己写了个兼容性一般的代码,大家可以来讨论下 原来我用的是从pjblog上的 代码如下: //查找网页内宽度太大的图片进行缩放以及PNG纠正 function ReImgSize(){ for (i=0;i { if (document.all){ if (document.images[i].width>550) { document.images[i].width="550" //没有高,明显会让图片变形 try{ document.images[i].outerHTML=''+document.images[i].outerHTML+'' }catch(e){} } } else{ if (document.images[i].width>400) { //宽和高都没有,更是让firefox下图片撑大图片 document.images[i].title="在新窗口打开图片" document.images[i].style.cursor="pointer" document.images[i].onclick=function(e){window.open(this.src)} } } } }
非常好用的代码可不足的地方就是firefox下大图会变形,而且无法控制区域的图片,如果想要的大图,也被变成小图了 我自己写了个, 代码如下: function $(objectId) { if(document.getElementById && document.getElementById(objectId)) { // W3C DOM return document.getElementById(objectId); } else if (document.all && document.all(objectId)) { // MSIE 4 DOM return document.all(objectId); } else if (document.layers && document.layers[objectId]) { // NN 4 DOM.. note: this won't find nested layers return document.layers[objectId]; } else { return false; } } function dxy_ReImgSize(){ var box=$("dxy_content"); var imgall=box.getElementsByTagName("img") for (i=0;i { if (imgall[i].width>500) { var oWidth=imgall[i].width; var oHeight=imgall[i].height; imgall[i].width="500"; imgall[i].height=oHeight*500/oWidth; } } }
可又发现,如果低浏览器,不支持getElementsByTagName,就没的玩了,好处是可以控制区域. 最后没办法了,就先弄个,暂时的解决办法 代码如下: function ReImgSize(){ for (i=0;i { if (document.all){ if (document.images[i].width>500) { var oWidth=document.images[i].width; var oHeight=document.images[i].height; document.images[i].width="500"; document.images[i].height=oHeight*500/oWidth; document.images[i].outerHTML=''+document.images[i].outerHTML+'' } } else{ if (document.images[i].width>500) { var oWidth=document.images[i].width; var oHeight=document.images[i].height; document.images[i].width="500"; document.images[i].height=oHeight*500/oWidth; document.images[i].title="在新窗口打开图片"; document.images[i].style.cursor="pointer" document.images[i].onclick=function(e){window.open(this.src)} } } } }
注意我增加了 代码如下: var oWidth=document.images[i].width; var oHeight=document.images[i].height; document.images[i].width="500"; document.images[i].height=oHeight*500/oWidth;