本文實(shí)例講述了JavaScript簡單獲取頁面圖片原始尺寸的方法。分享給大家供大家參考,具體如下:
這里通過Image()對(duì)象獲取原始寬高
這種方式就沒有那么麻煩,直接new一個(gè)Image()對(duì)象,然后把img的src賦值給他即可獲取。
var img = new Image();
img.src = $("#target").attr("src");
if(img.complete){
alert('width:'+img.width+',height'+img.height);
img = null;
}else{
img.onload = function(){
alert('width:'+img.width+',height'+img.height);
img = null;
};
}
并且不要擔(dān)心new Image對(duì)象會(huì)多一個(gè)http請(qǐng)求,瀏覽器加載圖片后已經(jīng)有緩存,你new N個(gè)image對(duì)象都沒問題,當(dāng)然,內(nèi)存會(huì)消耗,所以用完后img置為null。
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。