[英]jQuery image height/width in Chrome
我正在嘗試獲取圖像的寬度/高度以設置父容器的寬度/高度。 這是我這樣做的代碼:
var current_img = temp.find(".test-img").attr('src', c['img']).addClass("active-image");
然后我通過
current_img.css('width');
我遇到的問題是 chrome 在圖像之前加載 jscript,因此 function 返回 null。 所以我把這段代碼放在一起:
$(".test-img").each(function (index) {
$(this).load(function() {
imgwidth = $(this).css('width');
imgheight = $(this).css('height');
if (imgwidth != "0px" && imgheight != "0px")
$(this).parent().addClass('center').css({'width' : imgwidth, 'height' : imgheight});
});
});
第一次加載頁面時這似乎工作正常,但是當調用 function 時,它返回 null。 此外,當我在本地打開頁面時,它似乎工作正常,但是當托管在我的網絡服務器上時,我遇到了這個問題。
好的,經過大量研究,我找到了解決方案。 這並不完美,但迄今為止我想出的最好的。
var img = new Image(); //create new image
$(img).append("div").fadeIn('fast', function() { //We use the callback function from fadein
var width = $(img).width();
var height = $(img).width();
});
此解決方法依賴於 fadeIn 將僅在正確加載圖像后執行 function。 我的問題是我正在清空包含圖像的 div 並重新填充它,但它仍然緩存在瀏覽器中。 所以 img.load() 沒有做任何事情,因為它檢測到圖像確實已加載。
可以停止對已經存在於瀏覽器緩存中的圖像進行觸發
希望這可以幫助!
使用$('img').css('width')
你得到圖像樣式的寬度屬性值而不是實際圖像的寬度,使用$('img').width()
代替。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.