开发者

Jquery find image height not working

开发者 https://www.devze.com 2022-12-18 03:01 出处:网络
I\'m trying to use jQuery to find the image height of the first \"grand children\" of a container, then set the container to that height.But, I can\'t seem to pull the image height attribu开发者_Go百科

I'm trying to use jQuery to find the image height of the first "grand children" of a container, then set the container to that height. But, I can't seem to pull the image height attribu开发者_Go百科te - getting the src works. Any ideas? Is it just trying to pull the heights via CSS? How do i get the "real heights" I can't input the width and height in img tag - so that's not an option ;(

 $(document).ready(function() {
       var imageContainer = '#image-container';


       var imageSrc = $(imageContainer).children(':first').children(':first').attr('src'); // control test
       var imageHeight = $(imageContainer).children(':first').children(':first').height(); // have also tried attr('height')

       alert(imageSrc + ' ' + imageHeight);

    });


    <div id="image-gallery">
      <div id="image-container">    

        <div class="slide">
          <img src="test1.jpg" alt="test1" />
          <p>
            <strong>This is a test 1</strong>
          </p>
        </div>

        <div class="slide">
         <img src="test2.jpg" alt="test2" />
         <p>
           <strong>This is a test 2</strong>
         </p>
       </div>

      </div>
    </div>


From the API docs:

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

So instead of executing your script in $(document).ready(); use $(window).load(); or better yet, $(image).load();. For example:

$(document).ready(function() {
    var imageContainer = '#image-container';

    $(imageContainer).children(':first').children(':first').load(function() {
        var imageSrc = $(this).attr('src'); // control test
        var imageHeight = $(this).height(); // have also tried attr('height')

        alert(imageSrc + ' ' + imageHeight);
    });
});


you should wait until your image is loaded - something along the line of

 $('#imageContainer').children(':first').children(':first').load(function() {
     alert($(this).height());
 });


The reason that you can't get the size of the images is that they don't have any size yet. The code runs after the page has loaded but before the images has loaded.

Run the part of the code that needs the image size after all elements in the page are loaded:

$(window).load(function () {
  ...
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号