首页  ·  知识 ·  前端
css来强制按比例压缩图片的高度或宽度
hankx  http://hi.baidu.com/hankx/    编辑:dezai  图片来源:网络
有时候图片太大,会破环网页整齐的布局。这时可以用css来强制按比例压缩图片的高度或宽度css代码如下:,a {border:0; 0;

有时候图片太大,会破环网页整齐的布局。这时可以用css来强制按比例压缩图片的高度或宽度
css代码如下:

img,a img{
border:0;
margin:0;
padding:0;
max-width:590px;
width:expression(this.width>590?"590px":this.width);
max-height:590px;
height:expression(this.height>590?"590px":this.height);
}

这样当图片的高度或宽度若超过590px,将会按比例压缩成590px,如果不超过则按原大小显示。

不过我习惯使用js方法,用Jquery更简单:

//图片缩放
function ShowImage(ImgD,proMaxWidth,proMaxHeight){
var image=new Image();
image.src=ImgD.src;

if(image.width>0 && image.height>0){
   var rate = (proMaxWidth/image.width < proMaxHeight/image.height)?proMaxWidth/image.width:proMaxHeight/image.height;
  
   if(rate <= 1){   
    ImgD.style.width = image.width*rate;
    ImgD.style.height =image.height*rate;
    //垂直居中
    ImgD.style.marginTop=((proMaxHeight-image.height*rate)/2)+"px";
    ImgD.style.marginBottom=((proMaxHeight-image.height*rate)/2)+"px";
   
   }
   else {
    ImgD.style.width = image.width;
    ImgD.style.height =image.height;
    //垂直居中
    ImgD.style.marginTop=((proMaxHeight-image.height)/2)+"px";
    ImgD.style.marginBottom=((proMaxHeight-image.height)/2)+"px";
   }
}
}

这个函数可以直接使用在图片的onload上,但是如果使用jquery可以做一个插件函数:

jQuery.fn.extend({
ShowImage:function(maxWidth,maxHeight){
   return this.find("img").each(function(){
    ShowImage(this,maxWidth,maxHeight);          
   });
}
});

假如理想控制id为 ImageList的内容区域中的图片,这样写:

$("#ImageList").ShowImage(80,80);

本文作者:hankx 来源:http://hi.baidu.com/hankx/
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读