在网站中通常要显示各种尺寸的图片,但图片的尺寸不一定符合显示的要求。如果直接指定img的width和height属性的话图片又很可能会被挤压的变形。下面这个代码可以把图片放进一个imgBox,并根据imgBox的大小来按比例缩放图片以适应他,同时图片会在imgBox中居中显示。来看代码:
首先是HTML:
<!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" />
<title>按比例自动缩放图片</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/drawImg"></script>
</head>
<body>
<div id="imgBox" style="width:500px; height:400px; background:#cccccc; overflow:hidden">
<img id="img1" alt="" src="images/1.jpg" onload="DrawImg(500,400);" />
</div>
</body>
</html>
再是JavaScript: