javascript - Jquery 查找图像高度不工作

标签 javascript jquery css image height

我正在尝试使用 jQuery 查找容器的第一个“孙子”的图像高度,然后将容器设置为该高度。但是,我似乎无法提取图像高度属性 - 让 src 起作用。有任何想法吗?它只是想通过 CSS 来拉高吗?我如何获得“真实高度”我无法在 img 标签中输入宽度和高度 - 所以这不是一个选项;(

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

最佳答案

来自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.

因此,不要在 $(document).ready(); 中执行脚本,而是使用 $(window).load(); 或更好的方法, $(图像).load();。例如:

$(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);
    });
});

关于javascript - Jquery 查找图像高度不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2150816/

相关文章:

jquery - Ajax 评论表单未返回 ExpressionEngine 成功模板内容

jquery - 是否可以将折扣代码从购物车页面发送到 Shopify 的结账页面?

html - Heroku:在应用程序启动时显示自定义页面

html - 为什么我的按钮没有完全对齐?

jquery - 将 Flexbox 与 jQueryUI 的 sortable 结合使用

javascript - Css - 带有固定标题的侧边栏

javascript - CSS 首选高度和最大高度

javascript - 为什么 Controller 在 Ember 中是单例的?

javascript - IE 8 文档模式 :IE 8 standards 的正则表达式中应为 ']'

javascript - 我可以在对象的方法中使用对象的属性而不使用 `this`