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({ 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({ 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>
后记:
在公司项目里看到比例缩放图片的方法,改写成一个简单的jQuery插件。
只有三个简单的参数:
custom : false/true 是否根据父级容器宽高定义大小,只有为true时width,height两个参数才生效;
width : 目标放大的宽度;
height : 目标放大的高度;
代码解释 :
flag = old_width < old_height ? old_width / options.width : old_height / options.height
求出最小值的比例
this_width = old_width / flag,
this_height = old_height / flag;
根据比例算出正比例的值
if( this_width < options.width ){
this_width = width;
}
if( this_height < options.height ){
this_height = options.height;
}
预防值不够做的强制,不过会有点小拉伸
$this.css({ this_width, height: this_height});
赋值
var iTop = (this_height - options.height) * 0.3,
iLeft = (this_width - options.width) * 0.5;
求出偏移量
if ( old_width < old_height ) {
$this.css('margin-left', '0px');
$this.css('margin-top', '-' + iTop + 'px');
}else if( old_width > old_height ) {
$this.css('margin-left', '-' + iLeft + 'px');
$this.css('margin-top', 0);
}else{
$this.css('margin-left', 0);
$this.css('margin-top', 0);
}
赋值偏移量
$this.fadeIn();
渐显图片