tips:图片自适应大小,绝对居中javascript实现
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 5 <title>图片居中显示</title> 6 <style> 7 .box{ position: relative; width:300px; height:300px; border:1px solid #ccc; float:left; margin:5px;} 8 .box img{ position: absolute;top:50%; left:50%;} 9 </style> 10 </head> 11 <body> 12 <script> 13 //获取id 14 function _$ (id) 15 { 16 return typeof id === "string" ? document.getElementById(id) : id; 17 } 18 //获取tagName 19 function _$$ (elem, oParent) 20 { 21 return (oParent || document).getElementsByTagName(elem); 22 } 23 function MakeCenter(){ 24 this.initi.apply(this,arguments); 25 } 26 MakeCenter.prototype = 27 { 28 //初始化 29 initi : function(obj,setWidth,setHeight){ 30 var _this = this; 31 this.imgMaxWidth = setWidth; 32 this.imgMaxHeight = setHeight; 33 this.obj = _$(obj); 34 this.imgs = _$$("img",this.obj); 35 for(var i=0; i<this.imgs.length; i++){ 36 if(this.imgs[i].complete) { 37 this.adjustImage.call(this.imgs[i],this.imgMaxWidth,this.imgMaxHeight); 38 } else { 39 this.imgs[i].onload = adjustImage(_this.imgMaxWidth,_this.imgMaxHeight); 40 } 41 } 42 }, 43 //计算图片的宽度高度设置图片的margin值 44 adjustImage : function(mw,mh){ 45 var w = this.offsetWidth, h = this.offsetHeight; 46 if(mw > 0 && w > mw) { 47 this.width = mw; 48 this.height = h/(w/mw); 49 } else if(mh > 0 && h > mh) { 50 this.height = mh; 51 this.width = w/(h/mh); 52 } 53 this.style.marginLeft = -this.width/2+"px"; 54 this.style.marginTop = -this.height/2+"px"; 55 } 56 57 } 58 window.onload = function(){ 59 new MakeCenter("box",200,100); 60 } 61 </script> 62 <div id="box"> 63 <div class = "box"> 64 <img src="http://www.zllg.net/themes/drfx_01/images/onclick/onclick.png" /> 65 </div> 66 <div class = "box"> 67 <img src="http://www.zllg.net/themes/drfx_01/images/may/content_1_01.jpg" /> 68 </div> 69 <div class = "box"> 70 <img src="http://www.zllg.net/themes/drfx_01/images/may/content_3.jpg" /> 71 </div> 72 </div> 73 </body> 74 </html>