css实现图片等比例缩放在不同的浏览器中会出现细微的差别,即浏览器兼容性,下面即为css控制图片缩放的代码。
要实现图片等比例缩放效果,对于标准的浏览器,只需要在文件的头部(即head部分)加入css样式来控制图片的效果即可:
<style>
img {max-width:100px; max-height:100px;}
</style>
然而对于像IE6这样的非标准的浏览器而言,这句代码是不被IE6识别的,此时就需要通过JavaScript来控制了:
<script>
function DrawImage(ImgD,iwidth,iheight){
//参数(图片,允许的宽度,允许的高度)
var image=new Image();
image.src=ImgD.src;
if(image.width>0 && image.height>0){
if(image.width/image.height>= iwidth/iheight){
if(image.width>iwidth){
ImgD.width=iwidth;
ImgD.height=(image.height*iwidth)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}else{
if(image.height>iheight){
ImgD.height=iheight;
ImgD.width=(image.width*iheight)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
}
}
}
</script>
这样当图片在加载的时候给图片添加一个加载事件onLoad,同时需要给调用的函数传入相应的参数,如此一来就解决了浏览器兼容性的问题。
<img src="" border="0" alt="自动缩放后的效果" onLoad="javascript:DrawImage(this,"100","70");"/>
图片实现等比例缩放
最新推荐文章于 2024-09-14 18:52:56 发布