JavaScript簡單獲取頁面圖片原始尺寸的方法

字號:


    本文實(shí)例講述了JavaScript簡單獲取頁面圖片原始尺寸的方法。分享給大家供大家參考,具體如下:
    這里通過Image()對象獲取原始寬高
    這種方式就沒有那么麻煩,直接new一個Image()對象,然后把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對象會多一個http請求,瀏覽器加載圖片后已經(jīng)有緩存,你new N個image對象都沒問題,當(dāng)然,內(nèi)存會消耗,所以用完后img置為null。
    希望本文所述對大家JavaScript程序設(shè)計(jì)有所幫助。