基于jQuery的图片大小自动适应实现代码


关于
这个和以前弄的图片远处放大有许多相同的地方,比如图片预加载、有限容器显示无限大图片。

大小计算:内外两个比例。
复制代码 代码如下:

// 容器比例和图片比例
var dr = dw/dh, ir = iw/ih;
if(dr>ir){
ih = dh; iw = ih * ir;
}else{
iw = dw; ih = iw / ir;
}

居中显示:CSS绝对定位,负边距。
复制代码 代码如下:

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

加载中和加载出错:可自定义的参数。

HTML容器:
<div class="jq-img-autoresize" data-img-size="160,390" data-img-url="m1.jpg"></div>

如何使用:
复制代码 代码如下:

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

所有代码:
复制代码 代码如下:

/*
* 图片等比缩放
* @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(',');
// 容器宽高
var dw = size[0], dh = size[1];
var $img = $('<img />', { src : src }), img = $img[0];
var autoresize = function () {
if($el.data('img.complete')) return;
// 图片宽高
var iw = img.width, ih = img.height;
if(!iw || !ih) return;
// 比例
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);
}
})
};

演示地址:http://demo.phpstudy.net/js/imgAutoResizer/
打包下载:http://xiazai.phpstudy.net/201011/yuanma/imgAutoResizer.rar
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3