About
This is a lot of the same as the previous image, which is displayed in an infinitely large image than a pre-loaded image or a limited container.
Size Calculation: internal and external proportions.
Copy codeThe Code is as follows:
// Container proportion and image proportion
Var dr = dw/dh, ir = iw/ih;
If (dr> ir ){
Ih = dh; iw = ih * ir;
} Else {
Iw = dw; ih = iw/ir;
}
Center display: absolute CSS positioning, negative margin.
Copy codeThe Code is as follows:
Extends img.css ({width: iw, height: ih, position: 'absolute ', top: '000000', left: '000000', marginLeft:-iw/2, marginTop: -ih/2 })
Loading and loading errors: Customizable parameters.
HTML container:
<Div class = "jq-img-autoresize" data-img-size = "160,390" data-img-url = "m1.jpg"> </div>
How to use:
Copy codeThe Code is as follows:
$ ('Div. jq-img-autoresize'). imgAutoResizer ({
Loading: function () {$ (this). text ('loading ..');}
, Error: function () {$ (this). text ('invalid ..');}
});
All code:
Copy codeThe Code is as follows:
/*
* Proportional scaling of images
* @ By ambar
* @ Create 2010-11-17
* @ Update 2010-11-17
*/
$. Fn. imgAutoResizer = function (options ){
Return this. each (function (){
Var opt = $. extend ({
SizeAttr: 'Data-img-size'
, SrcAttr: 'Data-img-url'
, Error: null
, Loading: null
}, Options | {});
Var $ el = $ (this), src = $ el. attr (opt. srcAttr), size = $ el. attr (opt. sizeAttr). split (',');
// Container width and height
Var dw = size [0], dh = size [1];
Var $ img = $ ('', {src: src}), img = $ img [0];
Var autoresize = function (){
If ($ el. data ('img. complete') return;
// Picture width and height
Var iw = img. width, ih = img. height;
If (! Iw |! Ih) return;
// Proportion
Var dr = dw/dh, ir = iw/ih;
If (! (Dw> iw & dh> ih )){
If (dr> ir ){
Ih = dh; iw = ih * ir;
} Else {
Iw = dw; ih = iw/ir;
}
}
// Console. log (dr, ':', iw, '@', ih );
Cancel.data('img.complete', trueapps.css ({position: 'relative ', width: dw, height: dh, overflow: 'ddy '});
Extends img.css ({width: iw, height: ih, position: 'absolute ', top: '000000', left: '000000', marginLeft:-iw/2, marginTop: -ih/2 }). appendTo ($ el. empty ());
};
$ Img
. Load (autoresize)
. Error (function (){
If ($. isFunction (opt. error) opt. error. call ($ el );
});
If (img. complete ){
If (img. width & img. height) autoresize ();
} Else {
If ($. isFunction (opt. loading) opt. loading. call ($ el );
}
})
};
Demo address: http://demo.jb51.net/js/imgAutoResizer/
Package download: http://xiazai.jb51.net/201011/yuanma/imgAutoResizer.rar