同一段程式碼,在 IE 和 Firefox 跑得好好的,換到 Chrome 卻拿到 0。這是取圖片尺寸時最經典的坑,原因不在 jQuery,而在執行時機。
$(document).ready(function () {
var img_h = $img.height();
var img_w = $img.width();
});
圖片還沒下載完,尺寸自然是 0。
$(document).ready(function () {
$img.load(function () {
var img_h = $img.height();
var img_w = $img.width();
});
});
後端傳來一堆尺寸不一的圖,為了版面整齊,通常要在前端等比縮放。網路上常見的寫法如下:
$(document).ready(function () {
$('.post img').each(function () {
var maxWidth = 100, maxHeight = 100, ratio = 0;
var width = $(this).width();
var height = $(this).height();
if (width > maxWidth) { // 太寬
ratio = maxWidth / width;
$(this).css("width", maxWidth);
height = height * ratio;
$(this).css("height", height);
}
if (height > maxHeight) { // 太高
ratio = maxHeight / height;
$(this).css("height", maxHeight);
width = width * ratio;
$(this).css("width", width * ratio);
}
});
});
把這段放到自己的頁面實測,Chrome(當時 10.0.648.204)會出現圖片以原始尺寸顯示的 bug。解法是把整段包進 $(window).load()。
差別在觸發時機:
$(document).ready:HTML 解析完、DOM 就緒即執行,此時圖片、frame 等資源可能還在傳輸。$(window).load:整個頁面包含 frames、object、images 全部載入後才執行。因此在 Chrome 裡,圖片下載完成與 JS 執行的先後順序是不確定的;改用 load 之後,順序才有保證。
實務上有時連 $(this).width() 都會報「沒有 width 方法」,多半是 this 被當成原生元素。改成先 new 一個 Image 讀取真實尺寸,再回寫到畫面上的 img,可靠性更高:
jQuery(window).load(function () {
jQuery("div.product_info img").each(function () {
DrawImage(this, 680, 1000);
});
});
function DrawImage(ImgD, FitWidth, FitHeight) {
var image = new Image();
image.src = ImgD.src;
if (image.width > 0 && image.height > 0) {
if (image.width / image.height >= FitWidth / FitHeight) {
if (image.width > FitWidth) {
ImgD.width = FitWidth;
ImgD.height = (image.height * FitWidth) / image.width;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
} else {
if (image.height > FitHeight) {
ImgD.height = FitHeight;
ImgD.width = (image.width * FitHeight) / image.height;
} else {
ImgD.width = image.width;
ImgD.height = image.height;
}
}
}
}
一句話總結:凡是依賴圖片實際尺寸的程式,都該放在 load 之後,或者直接從 Image 物件取值,別相信 ready 階段拿到的數字。