js 完成對圖片的等比例縮放的方法

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   os   sp   on   div   

 1 /* 2     重新按比例設定 頁面上對應圖片的長和高, 3  */ 4 function resetImgSize(id,imgWidth,imgHeight,posWidth,posHeight) { 5     var width = 0; 6     var height = 0; 7     // 按比例縮小圖片的演算法 8     if(imgWidth > imgHeight) { 9         if(imgWidth > posWidth) {10             width = posWidth;11             height = imgHeight/imgWidth * width;12             13         }else {14             width = imgWidth;15             height = imgHeight;16         }17     }else {18         if(imgHeight > posHeight) {19             height = posHeight;20             width = (imgWidth/imgHeight) * height;21         }else {22             width = imgWidth;23             height = imgHeight;24         }25     }26     width = Math.floor(width);27     height = Math.floor(height);28     $(‘#‘+id).attr(‘width‘,width);29     $(‘#‘+id).attr(‘height‘,height);30     $(‘#‘+id).css(‘padding-left‘,(posWidth-width)/2);31     $(‘#‘+id).css(‘padding-top‘,(posHeight-height)/2);32 33 }34 35 /*36     擷取圖片尺寸37     imgURL  圖片載入地址38     posId   圖片位置id39     posWidth 放在圖片位置的width40     posHeight 放在圖片位置的height41  */42 43 function getImgSize(imgURL,posId,posWidth,posHeight) {44 45     var img = new Image();46      47 48     img.src = imgURL+‘?‘+Math.random();49     var width = 0;50     var height = 0;51     52 53     var check = function(){54 55         if(img.width > 0) {56 57         clearInterval(set);58         59         resetImgSize(posId,img.width,img.height,posWidth,posHeight);60         }61     };62      63     var set = setInterval(check,40);64 65     img.onload = function(){66         67         clearInterval(set);68     };69 70     71 }72 73 $(function(){74     $(‘.resetsize‘).each(function(){75         getImgSize(this.src,this.id,168,168);76     });77 });

 

js 完成對圖片的等比例縮放的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.