昨天群里的一位同学出了一个需求:在一固定的div中,图片如果大于div则实现等缩放,如小于则按原大小显示.2、不管前面那种情况,图片都要上下左右居中于div.
于是,动手写了下面的代码...
错误处不清楚,能力有限,期待高手批...
XML/HTML代码
- <style>
- #aideOne {width:500px;height:500px;position:relative;border:1px solid #f4f4f4;padding:4px;}
- #aideOne img {position:absolute;}
- </style>
- 原图:<br />
- <img src="http://www.lusisi.com/attachments/date_201001/1bd618b9abd8343225d14c1354b47047.png" alt="原图" />
- <br />
- <br />
- 缩放后的图片:<br />
- <div id="aideOne">
- <img id="aideimg" src="http://www.lusisi.com/attachments/date_201001/1bd618b9abd8343225d14c1354b47047.png" alt="" onload="aimg(this,500,500);" />
- </div>
- <script type="text/javascript">
- <!--
- function aimg(Img,maxWidth,maxHeight){
- var image=new Image();
- image.src=Img.src;
- var aiw = image.width;
- var aih = image.height;
- if(aiw>0 && aih>0){
- if(aiw/aih>= maxWidth/maxHeight){
- if(aiw>maxWidth){
- Img.width=maxWidth;
- Img.height=(aih*maxWidth)/aiw;
- }else{
- Img.width=aiw;
- Img.height=aih;
- }
- } else{
- if(aih>maxHeight){
- Img.height=maxHeight;
- Img.width=(aiw*maxHeight)/aih;
- }else{
- Img.width=aiw;
- Img.height=aih;
- }
- }
- }
- var ai = document.getElementById("aideOne");
- var aideimg = document.getElementById("aideimg");
- var h = ai.offsetHeight;
- var w = ai.offsetWidth;
- var ih =aideimg.offsetHeight;
- var iw =aideimg.offsetWidth;
- aideimg.style.top= (h-ih)/2+"px";
- aideimg.style.left= (w-iw)/2+"px";
- }
- //-->
- </script>
这里有个 demo

