標籤: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 完成對圖片的等比例縮放的方法