图片自动适应容器大小 – jquery+CSS

jquery部份:

//autoImage
;(function($){
$.extend({
“autoImage” : function(options){
options = options || {};
options = $.extend({
“parent”         : null,
“loadClassId”    : “<img src=’/images/loading.gif’ align=’absmiddle’ />图片载入中…”,
“src”            : “”,
“url”            : “”,
“alt”            : “”
},options);
var parent = options.parent;
if(parent == null || parent.length == 0) return;
parent.addClass(options.loadClassId);
var url = (options.url) ? options.url : options.src;
if(options.src) parent.html(“<a href='”+url+”‘ title='”+options.alt+”‘ target=’_blank’><img alt='”+options.alt+”‘ /></a><br /><div class=’altbig’>”+options.alt+”</div>”);
var image   = parent.find(“img”);
var src     = (options.src) ? options.src : image.attr(“src”);
var img     = new Image();
img.src     = src;

if(img.complete){
image.attr(“src”,img.src);
parent.removeClass(options.loadClassId);
imgAuto();
return;
}

image.attr(“src”,””);
image.hide();
$(img).load(function(){
imgAuto();
image.attr(“src”,this.src);
image.fadeIn(“normal”,function(){
parent.removeClass(options.loadClassId);
});
});

function imgAuto(){
var width   = img.width;
var height  = img.height;
var pwidth  = parent.width();
var pheight = parent.height();
if(width>0 && height>0){
var rate = (pwidth/width < pheight/height) ? pwidth/width : pheight/height;
if(rate <= 1){
width  *=  rate;
height *=  rate;
}
var left = (pwidth – width) * 0.5;
var top  = (pheight – height) * 0.5;
image.css({
//    “margin-left” : left + “px”,
“margin-top”  : top + “px”,
“width”       : width + “px”,
“height”      : height + “px”
});
}
}

}
});
$.fn.extend({
“autoImage” : function(src,url,alt,loadClassId){
return this.each(function(){
$.autoImage({
“parent”      : $(this),
“src”         : src,
“url”         : url,
“alt”         : alt,
“loadClassId” : loadClassId
});
});
}
});
})(jQuery);

CSS部份:

width:  /*设置容器宽度*/
height:  /*设置容器高度*/
overflow: hidden;


发表评论?

1 条评论。

  1. 看得很不是明白

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>