|
/*!
@FileOverview 擷取圖片尺寸
@date 2010/11/29
@param cfg 配置項,cfg.img為一個圖片對象的引用或者圖片的url,cfg.oncomplete為擷取尺寸後的後續操作,即回呼函數。具體應用請看例子
@return none
*/
function getImageSize(cfg){
var img=document.createElement('img'),
callback=cfg.oncomplete;
img.src = typeof cfg.img == 'string'?cfg.img:cfg.img.src;
img.setAttribute('style','position:absolute;visibility:hidden;');
document.body.appendChild(img);
img.onload=img.onerror=img.onreadystatechange=function(){
if(img&&img.readyState&&img.readyState!='loaded'&&img.readyState!='complete')
return;
img.onload = img.onreadystatechange = img.onerror = null;
callback.call({"width":img.width,"height":img.height},null);
img.parentNode.removeChild(img);
img=null;
};
}
/* 例子1,擷取遠程圖片的尺寸 */
getImageSize({
img:'http://www.qiqiboy.com/wp-content/uploads/2010/11/bing.png',
oncomplete:function(){
alert('寬度:'+this.width+','+'高度:'+this.height)
}
});
/* 例子2,限制class為myimg的圖片的大小為600以內 */
var imgs=getElementsByClassName('myimg','img',document),//getElementsByClassName為一個自寫的結點擷取方法,不是JS原生支援的哦
maxWidth=600;//最大寬度為600
for(var i=0;i<imgs.length;i++){
getImageSize({
img:imgs[i],
oncomplete:function(){
if(this.width>maxWidth){
imgs[i].height=Math.round(this.height/this.width*maxWidth);
imgs[i].width=maxWidth;
}
}
});
} |