简体   繁体   中英

jQuery gets the image height before the image is loaded?

I have looked around and tried many solutions, but jquery still tries to get the image height before the image is loaded:

$('img').load(function(){
    var heightStart = $(".carousel .carousel-inner img").height();
    alert(heightStart); // 0
});

I always get an 0 . Any ideas what is the best way of doing this?

I even have tried with the plain js:

    var i = new Image()
    i.src = "images/xxx.jpg";
    var h = i.height
    alert(heightStart); // 464

It gets the image height but the number is wrong! The number is always smaller but the image has a long height.

EDIT:

the images have not height and width attributes:

<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>

My image height is 464 so new Image() is correct . but the problem is that the image has been resized on the large screen with img-responsive .

$('img').load(function(){
    alert($(this).height());
});

or

var i = new Image()
i.src = "images/xxx.jpg";
i.onload = function() { alert(this.height) };

A little explanation to go with the answer - your first function registers onload listeners to all present img elements that alerts the first matched img element within .carousel .carousel-inner 's height, which might be 0, who knows.

The problem with your vanilla example is that you are trying to alert the height before the image is done loading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM