让图片自适应大小的方法

参考:http://www.cnblogs.com/mrhgw/archive/2006/10/18/532099.html

就像参考文档中提至的,对于图片的宽度谷歌获取好像需要onload,无奈下只能在这个元素中定义宽度解决问题。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    </head>
<body>
<img  id="achome" width="550" height="734" src="http://image2.sina.com.cn/ent/y/2006-10-09/U1819P28T3D1276435F326DT20061009152013.jpg" />


<script>
    var imageArr =document.getElementById("achome");

    var imageRate = imageArr.offsetWidth / imageArr.offsetHeight; 
  
   //alert(imageRate);

    if(imageArr.offsetWidth > 200)
    {
        imageArr.style.width=200 + "px";
        imageArr.style.height=200 / imageRate + "px";
    }
   
    if(imageArr.offsetHeight > 500)
    {
        imageArr.style.width =500 * imageRate + "px";
        imageArr.style.height = 500 + "px";
    }

</script>
</body>
</html>
原文地址:https://www.cnblogs.com/wowchky/p/3354952.html