【问题标题】:Jquery find image height not workingJquery查找图像高度不起作用
【发布时间】:2011-01-10 04:26:09
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

    标签: javascript jquery css image height


    【解决方案1】:

    你应该等到你的图片被加载——类似于

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

    【讨论】:

      【解决方案2】:

      您无法获取图像大小的原因是它们还没有任何大小。代码在页面加载之后但在图像加载之前运行。

      页面中所有元素都加载完毕后,运行需要图片大小的部分代码:

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

      【讨论】:

        【解决方案3】:

        来自API docs

        如果代码依赖于加载的资源(例如,如果需要图像的尺寸),则应将代码放在加载事件的处理程序中。

        因此,不要在$(document).ready(); 中执行您的脚本,而是使用$(window).load(); 或更好的$(image).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);
            });
        });
        

        【讨论】:

        • $(image).load(); 不适合我 - “图像未定义”错误
        • 我相信你需要做$('img').load();
        猜你喜欢
        • 1970-01-01
        • 2012-05-03
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 2020-10-05
        • 1970-01-01
        • 2021-03-08
        • 1970-01-01
        相关资源
        最近更新 更多