在实际应用中,图片自适应大小结合水平垂直居中,是非常常用的手段。今天就图片的自适应这里推荐一个方法,此方法已经通过多种常见场合和各大浏览器兼容性的测试。
先看方法:
-
* auto resize image
-
* @param img img obj
-
* @param w custom width
-
* @param h custom height
-
*/
-
function resizeImage (img,w,h ) {
-
//remove default attribute
-
img. removeAttribute ( "width" );
-
img. removeAttribute ( "height" );
-
var pic;
-
//if is ie
-
if (window. ActiveXObject ) {
-
var pic= new Image ( );
-
pic. src=img. src;
-
} else pic=img;
-
if (pic & & pic. width & & pic. height & & w ) {
-
if ( !h ) h=w;
-
if (pic. width >w ||pic. height >h ) {
-
var scale=pic. width /pic.height,fit=scale>=w/|>h;
-
if (window. ActiveXObject ) img=img. style;
-
img [fit? 'width': 'height' ]=fit?w:h;
-
//if is ie6
-
if (window. ActiveXObject )
-
img [fit? 'height': 'width' ]= (fit?w:h ) * (fit? 1 /scale:scale );
-
}
-
}
-
};
这个方法一共测试了3种场合:
场合1,直接作用在img标签上:
<img src=”http://img.china.alibaba.com/images/trade/other/091231/test1.jpg” width=”400″ height=”900″ οnlοad=”resizeImage(this,400,300)” />
场合2,对现有标签重置src属性:
<img id=”test2″ src=”about:blank” />
var test2=document.getElementById(‘test2′);
test2.οnlοad=function(){ resizeImage(test2,400); };
test2.src=’http://img.china.alibaba.com/images/trade/other/091231/test2.jpg’;
场合3,动态加载img:
var test3=new Image();
test3.οnlοad=function(){ resizeImage(test2,300); };
test3.src=’http://img.china.alibaba.com/images/trade/other/091231/test3.jpg’;
document.appendChild(test3);
以上3种所演绎的情况在技术层面的差别主要有:
1. img是否存在与页面上,在ie6下,对不存在页面上的img的宽高自适应,对2个属性都必需进行设定。
2. img是否自带width, height属性,在不删除原有属性的前提下,通过js设定图片的宽高将会失效
3. img在onload的过程中是否可见,在ie6下,对不可见的img在onload中无法获取图片的宽高属性。
同时需要注意的是,在Opera和Chrome浏览器下,没有设置宽高属性的图片是在DOM Ready之后进行load的,所有请使用此方法的同学注意方法调用的时机。