指定地區的圖片自動按比例縮小的js代碼(防止頁面被圖片撐破)

來源:互聯網
上載者:User

複製代碼 代碼如下:
<div id=article><img height="800" alt="" width="1280" src="/down/js/images/12498880470.jpg" /></div>
<script type="text/javascript" >
//縮放圖片到合適大小
function ResizeImages()
{
   var myimg,oldwidth,oldheight;
   var maxwidth=550;
   var maxheight=880
   var imgs = document.getElementById('article').getElementsByTagName('img');   //如果你定義的id不是article,請修改此處

   for(i=0;i<imgs.length;i++){
     myimg = imgs[i];

     if(myimg.width > myimg.height)
     {
         if(myimg.width > maxwidth)
         {
            oldwidth = myimg.width;
            myimg.height = myimg.height * (maxwidth/oldwidth);
            myimg.width = maxwidth;
         }
     }else{
         if(myimg.height > maxheight)
         {
            oldheight = myimg.height;
            myimg.width = myimg.width * (maxheight/oldheight);
            myimg.height = maxheight;
         }
     }
   }
}
//縮放圖片到合適大小
ResizeImages();
</script>


意思就是控制指定地區的的圖片大小,要不一些大點的廣告圖片也會變形。

指令碼之家用的圖片控制碼:

複製代碼 代碼如下:
function controlImg(ele,w,h){
  var c=ele.getElementsByTagName("img");
  for(var i=0;i<c.length;i++){
    var w0=c[i].clientWidth,h0=c[i].clientHeight;
    var t1=w0/w,t2=h0/h;
    if(t1>1||t2>1||w0>=600){
     c[i].width=Math.floor(w0/(t1>t2?t1:t2));
     c[i].height=Math.floor(h0/(t1>t2?t1:t2));
if(document.all){
          c[i].outerHTML='<a href="'+c[i].src+'" target="_blank" title="在新視窗查看圖片">'+c[i].outerHTML+'</a>'
      }
       else{
          c[i].title="在新視窗開啟圖片";
          c[i].onclick=function(e){window.open(this.src)}
           }
           }
    }
 }

ele就是指定的地區,w是最大的寬度,大於這個就會縮小。h是最大的高度。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.