template design by http://www.20shx.com/
时间:2013-12-25 发布人:SHX 浏览次数:3473 评论:0
在前台排版时,经常需要把图片高宽定死才能保持显示在指定的范围内。但这样如果比例改变就会强制把图片拉伸变形,这里有几种自动适应的方式:
第一中方式:(不能完全适应)
// JavaScript Document //<img src="#" width="95" AutoSize="ResizeImage(this, 95, 95);"/> function AutoSize(ImgD,MaxWidth,MaxHeight) { var image=new Image(); image.src=ImgD.src; if(image.width>0 && image.height>0) { flag=true; if(image.width/image.height>= MaxWidth/MaxHeight) { if(image.width>MaxWidth) { ImgD.width=MaxWidth; ImgD.height=(image.height*MaxWidth)/image.width; } else { ImgD.width=image.width; ImgD.height=image.height; } //ImgD.alt="原始尺寸:宽" + image.width+",高"+image.height; } else { if(image.height>MaxHeight) { ImgD.height=MaxHeight; ImgD.width=(image.width*MaxHeight)/image.height; } else { ImgD.width=image.width; ImgD.height=image.height; } //ImgD.alt="原始尺寸:宽" + image.width+",高"+image.height; } } }
第二种方式:(不兼容浏览器)
/*------------------------------------------------------------------------------ *调用方式:$(selector).resizeImg({w:maxWidth,h:maxHeight}) -------------------------------------------------------------------------------- */ (function($){ $.fn.extend({ resizeImg:function(opt,callback){ var defaults={w:200,h:150}; var opts = $.extend(defaults, opt); this.each(function(){ $(this).load(function(){ var imgWidth=this.width,imgHeight=this.height; if(imgWidth>opts["w"]){ this.width=opts["w"]; this.height=imgHeight*(opts["w"]/imgWidth); imgWidth=opts["w"]; imgHeight=this.height; } if(imgHeight>opts["h"]){ this.height=opts["h"]; this.width=imgWidth*(opts["h"]/imgHeight); imgHeight=opts["h"]; imgWidth=this.width; } //水平居中,垂直居中 $(this).css({"margin-top":(opts["h"]-imgHeight)/2,"margin-left":(opts["w"]-imgWidth)/2}); }); }); } }); })(jQuery);
第三种就可以完全适应了:
// JavaScript Document $(window).load(function(){ $("img[name='picautozoom']").each(function(){ if(this.complete){ var smallWidth=$(this).width(); var smallHeight=$(this).height(); $(this).width(smallWidth).css("height","auto"); if($(this).height()>smallHeight){ $(this).height(smallHeight).css("width","auto"); $(this).css("padding","0px "+Math.floor(Math.abs((smallWidth-$(this).width())/2))+"px");} else{ $(this).css("padding",Math.floor(Math.abs((smallHeight-$(this).height())/2))+"px 0px");}}}); }); /** <img src='*.jpg' width='150' height='150' name='picautozoom' /> **/
上一篇:QQ中的神奇日志解读下一篇:彩票,股票的api的获取