Demo : Demo

Demo截图:

图片比例缩放小插件

 

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <style>
 7     *{ margin:0;padding:0; }
 8     .box{ margin:100px auto; width:80px; height:80px;overflow:hidden; }
 9     </style>
10     <script src="https://code.jquery.com/jquery-1.8.3.js"></script>
11     <script>
12     $(function(){
13 
14       $('img').scaling();
15 
16     });
17 
18     $.fn.scaling = function( opt ){
19 
20       var ops = {
21              'custom' : false,
22              'width'  : 100, 
23              'height' : 100
24           };
25 
26       var options = $.extend(ops,opt);
27 
28       $(this).each(function() {
29 
30         var $this = $(this);
31 
32         if( !options.custom ){
33           options.width  = $this.parent().width(); 
34           options.height = $this.parent().height();
35         }
36 
37         $this.css({ width: options.width+'px', height: options.height+'px'});
38         var img = new Image();
39         img.src = $this.attr('src');
40 
41         img.onload = function(){
42 
43           var old_width = img.width,
44               old_height = img.height,
45               flag = old_width < old_height ? old_width / options.width : old_height / options.height,
46               this_width = old_width / flag,
47               this_height = old_height / flag;
48 
49           if( this_width < options.width ){
50             this_width = width;
51           }
52 
53           if( this_height < options.height ){
54             this_height = options.height;
55           }
56 
57           $this.css({ width: this_width, height: this_height});
58 
59           var iTop = (this_height - options.height) * 0.3,
60               iLeft = (this_width - options.width) * 0.5;
61 
62           if ( old_width < old_height ) {
63 
64             $this.css('margin-left', '0px');
65             $this.css('margin-top', '-' + iTop + 'px');
66 
67           }else if( old_width > old_height ) {
68 
69             $this.css('margin-left', '-' + iLeft + 'px');
70             $this.css('margin-top', 0);
71 
72           }else{
73 
74             $this.css('margin-left', 0);
75             $this.css('margin-top', 0);
76 
77           }
78 
79           $this.fadeIn();
80 
81         };
82 
83         img.onerr = function(){
84 
85           img.src = $this.attr('src');
86 
87         };
88 
89       });
90 
91     };
92     </script>
93 </head>
94 <body>
95     <div class="box" >
96         <img src="http://static.cnblogs.com/images/logo_small.gif"   alt="">
97     </div>
98 </body>
99 </html>
View Code

相关文章: