×

限制图片的最大宽度和高度之解决办法

管理员 管理员 发表于2010-07-19 14:08:37 浏览3364 评论0

抢沙发发表评论

<html>
<head>
<style type="text/css">
<!--
   img.pic{
    max-width:300;
    max-height:100px;
    /*由于IE6.0以及以前版本的IE不支持上边两个属性,所以加上以下两条语句.这里要说明的是expression只有IE支持*/
    width: expression(this.width > 300 && this.width / 300 >= this.height / 100 ? 300 : true);
    height: expression(this.height > 100 && this.width / 300 < this.height / 100 ? 100 : true);

   }
//-->
</style>

</head>
<body>
   <div id="pic">  
   </div>
   <img class="pic" src="Blue hills.jpg" />
</body>
</html>

由于上边的代码中,设置最大的长宽是直接用数字的,这样再修改的时候十分不方便,所以做了以下修改:

<html>
<head>
<script type="text/javascript">
<!--
Object.MAX_WIDTH = 400;
Object.MAX_HEIGHT = 300;

-->
</script>
<style type="text/css">
<!--
   img.pic{
    max-width:300px;
    max-height:100px;
    width: expression(this.width > Object.MAX_WIDTH && this.width / Object.MAX_WIDTH >= this.height / Object.MAX_HEIGHT ? Object.MAX_WIDTH : true);
    height: expression(this.height > Object.MAX_HEIGHT && this.width / Object.MAX_WIDTH < this.height / Object.MAX_HEIGHT ? Object.MAX_HEIGHT : true);

   }
//-->
</style>

</head>
<body>
   <div id="pic">  
   </div>
   <img class="pic" src="Blue hills.jpg" />
</body>
</html>

这样的话,只需要修改Object.MAX_WIDTH和Object.MAX_HEIGHT这两个类变量就可以很方便的修改最大的长宽

群贤毕至

访客