您的位置:首页 > Web前端 > JQuery

jQuery图片大小自动适应

2010-11-17 11:08 489 查看

关于

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

大小计算:内外两个比例。

// 容器比例和图片比例
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);
}
})
};


查看预览:

/Files/ambar/demos/imgAutoResizer/demo.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: