圖片一定要載入完成才能知道它的寬度和高度,因此在 jquery 中,建議用 load 來取得相關的資訊,例如:
$('img').load(function(){
// 寬 this.width;
// 高 this.height;
});
不過這樣子有時候會遇到圖片沒載完偵測失敗,可以改利用以下方式:
var img = $("img")[0];
$("<img/>")
.attr("src", $(img).attr("src"))
.load(function() {
//寬 this.width;
//高 this.height;
});
另外利用 HTMLImageElement 屬性(properties),也可以用 .prop() 這個方法來取得相關圖片檔的資訊:
var $img = $("#myImage");
console.log(
$img.prop("naturalWidth") +'\n'+ // 實際寬度
$img.prop("naturalHeight") +'\n'+ // 實際高度
$img.prop("width") +'\n'+ // 呈現的寬度
$img.prop("height") +'\n' // 呈現的高度
);
注意:
- 其他屬性參考 https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement
- 此方式尚未完全支援各瀏覽器或行動裝置,因此要小心使用。