CSS控制图片等比例缩放

CSS控制图片等比例缩放

按比例缩小或者放大到某个尺寸,对于标准浏览器(如Firefox),或者最新都IE7浏览器,
直接使用max-width,max-height;或者min-width,min-height的CSS属性即可。如:

 代码如下 复制代码
img{max-width:100px;max-height:100px;}
img{min-width:100px;min-height:100px;}

对于IE6及其以下版本的浏览器,则可以利用其支持的expression属性,在css code中嵌入 code
来实现图片的缩放

 代码如下 复制代码

.thumbImage {max-width: 100px;max-height: 100px;} /* for Firefox & IE7 */
* html .thumbImage { /* for IE6 */
width: expression(this.width > 100 && this.width > this.height ? 100 : auto);
height: expression(this.height > 100 ? 100 : auto);
}

改写一下。

 代码如下 复制代码

#content img{height: expression(this.width > 600 ? this.height = this.height * 600 / this.width : “auto”);
width: expression(this.width > 600 ? “600px” : “auto”);
max-width:600px;}

在IE6、IE7下可以实际大图片按比例缩小,不会出现图片变形的情况,在FF和chrome下,expression无效,但通过max-width限制图片最大宽度,使页面不会被撑开。

css代码不可能兼容所有浏览器,后来找了一个js代码完美的解决了这些问题

 代码如下 复制代码

<script type=”text/javascript”>
function AutoResizeImage(maxWidth,maxHeight,objImg){
var img = new Image();
img.src = objImg.src;
var hRatio;
var wRatio;
var Ratio = 1;
var w = img.width;
var h = img.height;
wRatio = maxWidth / w;
hRatio = maxHeight / h;
if (maxWidth ==0 && maxHeight==0){
Ratio = 1;
}else if (maxWidth==0){//
if (hRatio<1) Ratio = hRatio;
}else if (maxHeight==0){
if (wRatio<1) Ratio = wRatio;
}else if (wRatio<1 || hRatio<1){
Ratio = (wRatio<=hRatio?wRatio:hRatio);
}
if (Ratio<1){
w = w * Ratio;
h = h * Ratio;
}
objImg.height = h;
objImg.width = w;
}
</script>

CSS控制图片等比例缩放

相关文章:

你感兴趣的文章:

标签云: