简体   繁体   中英

JavaScript/JQuery - How do I get img Height once new img src is loaded?

I have a custom carousel I'm working on, below is some parts of the code... It's huge so I won't bother with putting a full working example.

Anyway I passed a JSON object from php containing the file name of the images. When the right arrow is clicked, the element,

<img id="carousel_image" src="http://example.org/image/image.jpg" />

changes to a new src using jQuery,

$('#arrow_right').click(function(){
        $('#carousel_image').attr('src', storedSlides[currentSlide]);
        $('#carousel_image').ready(function(){
           console.log($('#carousel_image').height()); //returns 1000
        });
        console.log($('#carousel_image').height()); //returns 1000
    });

Both logs return 1000, the height of the original image prior to the click. How can I get the true height of the new image (once fully loaded)?

Thank you kindly for your help!

You need to use load event, not ready , ready is fired when the DOM is rendered. load is fired when the image is loaded on img elements.

http://www.w3schools.com/jsref/event_img_onload.asp

$('#arrow_right').click(function(){
    $('#carousel_image').attr('src', storedSlides[currentSlide]);
    $('#carousel_image').on("load", function(){
       console.log($('#carousel_image').height());
    });
    console.log($('#carousel_image').height());
});

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