一个兼容多种场合的Javascript图片大小自适应function

在实际应用中,图片自适应大小结合水平垂直居中,是非常常用的手段。今天就图片的自适应这里推荐一个方法,此方法已经通过多种常见场合和各大浏览器兼容性的测试。

先看方法:

/*
  1. * auto resize image
  2. * @param    img     img obj
  3. * @param    w       custom width
  4. * @param    h       custom height
  5. */
  6. function resizeImage (img,w,h ) {
  7.     //remove default attribute
  8.     img. removeAttribute ( "width" );
  9.     img. removeAttribute ( "height" );
  10.     var pic;
  11.     //if is ie
  12.     if (window. ActiveXObject ) {
  13.         var pic= new Image ( );
  14.         pic. src=img. src;
  15.     } else pic=img;
  16.     if (pic & & pic. width & & pic. height & & w ) {
  17.         if ( !h ) h=w;
  18.         if (pic. width >w ||pic. height >h ) {
  19.             var scale=pic. width /pic.height,fit=scale>=w/|>h;
  20.             if (window. ActiveXObject ) img=img. style;
  21.                 img [fit? 'width': 'height' ]=fit?w:h;
  22.             //if is ie6
  23.             if (window. ActiveXObject )
  24.                 img [fit? 'height': 'width' ]= (fit?w:h ) * (fit? 1 /scale:scale );
  25.         }
  26.     }
  27. };

这个方法一共测试了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的,所有请使用此方法的同学注意方法调用的时机。

转载于:https://my.oschina.net/blogsDdc/blog/103363

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值