js 完成对图片的等比例缩放的方法

 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   图片位置id
39     posWidth 放在图片位置的width
40     posHeight 放在图片位置的height
41  */
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)