Home >Web Front-end >JS Tutorial >Image size automatic adaptation implementation code based on jQuery_jquery

Image size automatic adaptation implementation code based on jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 18:16:131068browse
About
This has many similarities with the previous image zooming in from a distance, such as image preloading and limited containers displaying infinite images.

Size calculation: two ratios of inside and outside.
Copy code The 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;
}

Centered display: CSS absolute positioning, negative margins.
Copy code The code is as follows:

$img.css({width:iw,height: ih,position:'absolute',top:'50%',left:'50%',marginLeft:-iw/2,marginTop:-ih/2})

Loading and loading Error: Customizable parameters.

HTML container:

How to use:
Copy code The code is as follows:

$( 'div.jq-img-autoresize').imgAutoResizer({
loading : function () { $(this).text('loading..'); }
,error : function () { $( this).text('Invalid..'); }
});

All codes:
Copy code The code is as follows:

/*
* Image scaling
* @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;
// Image width and height
var iw = img.width, ih = img.height;
if(!iw || !ih) return;
// ratio
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);
$el.data('img.complete',true ).css({position:'relative',width:dw,height:dh,overflow:'hidden'});
$img.css({width:iw,height:ih,position:'absolute', top:'50%',left:'50%',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
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn