[英]jQuery gets the image height before the image is loaded?
我環顧四周並嘗試了許多解決方案,但jquery仍嘗試在加載圖像之前獲取圖像高度:
$('img').load(function(){
var heightStart = $(".carousel .carousel-inner img").height();
alert(heightStart); // 0
});
我總是得到0 。 有什么想法是最好的方法嗎?
我什至嘗試使用普通的js:
var i = new Image()
i.src = "images/xxx.jpg";
var h = i.height
alert(heightStart); // 464
它得到圖像的高度,但是數字錯誤! 該數字始終較小,但圖像的高度較長。
編輯:
圖像沒有高度和寬度屬性:
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
<div class="item active">
<img class="first-slide" src="images/xxx.jpg" alt="First slide" class="img-responsive">
<div class="container">
<div class="carousel-caption">xxx</p>
</div>
</div>
</div>
</div>
我的圖像高度是464
所以new Image()
是正確的 。 但是問題是圖像已在大屏幕上使用img-responsive
sensitive調整大小。
$('img').load(function(){
alert($(this).height());
});
要么
var i = new Image()
i.src = "images/xxx.jpg";
i.onload = function() { alert(this.height) };
答案有一個解釋-您的第一個函數.carousel .carousel-inner
偵聽器注冊到所有當前img
元素,這些警報會提醒.carousel .carousel-inner
高度.carousel .carousel-inner
的第一個匹配img
元素,該高度可能為0(知道)。
原始示例的問題在於,您試圖在圖像加載完成之前警告高度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.