Iamge固定居中于Div层中....

昨天群里的一位同学出了一个需求:在一固定的div中,图片如果大于div则实现等缩放,如小于则按原大小显示.2、不管前面那种情况,图片都要上下左右居中于div.

于是,动手写了下面的代码...

错误处不清楚,能力有限,期待高手批...

XML/HTML代码
  1. <style>  
  2. #aideOne {width:500px;height:500px;position:relative;border:1px solid #f4f4f4;padding:4px;}   
  3. #aideOne img {position:absolute;}   
  4. </style>  
  5.   
  6. 原图:<br />  
  7. <img src="http://www.lusisi.com/attachments/date_201001/1bd618b9abd8343225d14c1354b47047.png" alt="原图" />  
  8. <br />  
  9. <br />  
  10. 缩放后的图片:<br />  
  11. <div id="aideOne">  
  12. <img id="aideimg" src="http://www.lusisi.com/attachments/date_201001/1bd618b9abd8343225d14c1354b47047.png" alt="" onload="aimg(this,500,500);" />  
  13. </div>  
  14.   
  15. <script type="text/javascript">  
  16. <!--   
  17. function aimg(Img,maxWidth,maxHeight){   
  18.     var image=new Image();   
  19.     image.src=Img.src;   
  20.     var aiw = image.width;   
  21.     var aih = image.height;   
  22.     if(aiw>0 && aih>0){   
  23.         if(aiw/aih>= maxWidth/maxHeight){   
  24.             if(aiw>maxWidth){   
  25.                 Img.width=maxWidth;   
  26.                 Img.height=(aih*maxWidth)/aiw;   
  27.             }else{   
  28.                 Img.width=aiw;   
  29.                 Img.height=aih;   
  30.             }   
  31.         } else{   
  32.             if(aih>maxHeight){   
  33.                 Img.height=maxHeight;   
  34.                 Img.width=(aiw*maxHeight)/aih;   
  35.             }else{   
  36.                 Img.width=aiw;   
  37.                 Img.height=aih;   
  38.             }   
  39.         }   
  40.     }   
  41. var ai = document.getElementById("aideOne");   
  42. var aideimg = document.getElementById("aideimg");   
  43. var h = ai.offsetHeight;   
  44. var w = ai.offsetWidth;   
  45. var ih =aideimg.offsetHeight;   
  46. var iw =aideimg.offsetWidth;   
  47. aideimg.style.top= (h-ih)/2+"px";   
  48. aideimg.style.left= (w-iw)/2+"px";   
  49. }   
  50. //-->  
  51. </script>  

这里有个 demo

Tags: 居中, web标准

« 上一篇 | 下一篇 »

发表评论

注:网址请加上 http:// 若无,报错...

评论内容 (必填):