【问题标题】:How can i get the width/height of an image before appending that to the DOM/browser?在将图像附加到 DOM/浏览器之前,如何获取图像的宽度/高度?
【发布时间】:2011-10-31 04:14:42
【问题描述】:

我想在将图像附加到浏览器之前输出图像的宽度和高度。 当然,宽度为 0,高度为 0,因为图像尚未附加到 DOM。

我已将我的代码上传http://jsfiddle.net/BF5En/4/

如何在将图像附加到 DOM 之前获取正确的值??

谢谢,提前!

【问题讨论】:

    标签: jquery image height width append


    【解决方案1】:

    您的问题似乎很有趣。这是我谦虚的回答:

    $(document).ready(function() {
        $(".Photos a").click(function () {
            var href_attribute = $(this).attr('href');
            var new_item = $('<img src="' + href_attribute + '" />')
                .hide()
                .load(function () {
                    alert('Img was loaded! Width: ' + this.width + ' and height: ' + this.height);
                })
                .fadeIn(2000)
                .appendTo('.AppendingDiv');
            return false;
        });
    });
    

    现场示例:http://jsfiddle.net/hobobne/BF5En/10/

    你看,你必须确保图像是预加载的,为此我们使用.load()。否则你会得到0。这实际上很好,因为这意味着脚本可以工作,只是一切都很快,它可以得到尺寸。 .load() 确保首先加载图像,然后才接收尺寸。

    无论出于何种目的,你想使用尺寸,我建议在.load() 中也这样做。因为无论如何你可能会有多个.Photos a

    另外,您可能已经注意到您的.fadeIn(2000) 无法正常工作。那是因为,你的项目在你调用它之前就被附加了。如您所见,我为您修复了它:)

    注意!抱歉,我重命名了一些变量(让我脑子里的东西更符合逻辑。)

    【讨论】:

      【解决方案2】:
      var MyitemWidth = item.css('width');
      var MyitemHeight = item.css('height');
      

      看到这个答案Getting auto size of IMG before adding it to DOM (Using JQuery)

      DOM elements have dimensions only when added to a parent, as dimension is determined by the 
      rendering engine. To go around this issue, have a <div> container absolutely positioned off 
      screen, add the image to it first, get the dimension, then add the image at it's final destination.
      

      【讨论】:

      • 感谢您的回答,但我的高度和宽度仍然为零,因为图像尚未附加到浏览器
      • 感谢您的链接,据我了解,他们建议使用“绝对定位在屏幕外的容器”。这是该问题的唯一解决方案还是最佳解决方案?我对此有点困惑...如果我使用 .load() 函数,我会得到理想的结果吗?我的布局会不会被那个绝对定位的元素毁了??
      猜你喜欢
      • 2011-09-22
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2010-09-11
      • 2010-10-01
      相关资源
      最近更新 更多