js与自动伸缩图片 自动缩小图片的多浏览器兼容的方法总结

最近做一个图片的自动缩小效果,发现一直用的js,竟然在firefox下无法正常啊,导致页面变形.所以自己写了个兼容性一般的代码,大家可以来讨论下
原来我用的是从pjblog上的

//查找网页内宽度太大的图片进行缩放以及PNG纠正
 function ReImgSize(){
  for (i=0;i<document.images.length;i++)
   {
   if (document.all){
    if (document.images[i].width>550)
     {
       document.images[i].width="550"  //没有高,明显会让图片变形
       try{
           document.images[i].outerHTML='<a href="'+document.images[i].src+'" target="_blank" title="在新窗口打开图片">'+document.images[i].outerHTML+'</a>'
           }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<imgall.length;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<document.images.length;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='<a href="'+document.images[i].src+'" target="_blank" title="在新窗口打开图片">'+document.images[i].outerHTML+'</a>'
       }
   }
  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; 

如果大家发现了什么更好的方法,贴出来啊
www.laike.net 来客网 原创,转载请写明出处