在收集的dom元素上使用jquery获取图像的真实尺寸

时间:2014-10-31 17:35:30

标签: javascript jquery

我正在尝试在页面上获取图像的尺寸,以便进一步使用自定义“灯箱”或排序。但是,在尝试纯js方法和jquery方法时,我在变量上得到输出undefined。为什么是这样?是因为jquery加载事件?我尝试了onload并准备好了。

基本上我需要图像的完整尺寸来证明它是否应该加载到带有点击事件的灯箱中。

更新我现在能够从该功能获得控制台反馈,但它没有为我提供图像的尺寸。

$('.postbody').find('img').each(function() {
    var img = new Image(), width, height;
    $(img).load(function() {
        width = $(this).width();
        height = $(this).height();
        console.log('Width: '+width+' Height: '+height);
    });
    console.log($(this).attr('src'));
    img.src = $(this).attr('src');
});
#theater-box {
    display: none;
    position: fixed;
    width: auto;
    height: auto;
    min-width: 1005px;
    max-width: 1428px;
    padding: 10px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0,0,0,0.90);
    border: 2px solid rgba(255,255,255,0.4);
}

.postbody {
    width: 90%;
    height: 90%;
    background: rgba(100,50,50,0.5);
}

.postbody * img {
    width: 100%;
    max-width: 1168px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="theater-box"></div>

<div class="postbody">
    <div id="someclass"><img src="https://e8zzxa.bl3301.livefilestore.com/storageservice/passport/auth.aspx?sru=https:%2f%2fe8zzxa.bl3301.livefilestore.com%2fy2pDapooeiISgUV7-ugpyADuRULJ_stpkiALbypYJHjNxrhUqcvRsZ6eRk4PiJlClABLOfByjulDSDLOMCEpHhggVkgvM4z5Gdq0Jo-C0e1pCU%2fMajipoorHighlands2.jpg&wa=wsignin1.0" /></div>
</div>

4 个答案:

答案 0 :(得分:1)

异步设置变量并直接获取。 在伪代码中它有点像这样:

  1. 设置功能以在图像加载时检索宽度和高度
  2. 显示宽度和高度变量(尚未设置)
  3. 步骤1中设置的功能运行并设置变量。
  4. 因此,使用宽度和高度的代码应该在里面 image.load函数。 我希望它有所帮助,如果你有任何进一步的问题,请不要犹豫评论: - )

答案 1 :(得分:0)

也许您可以将console.log行作为$(img).load函数的最后一行。

答案 2 :(得分:0)

试试这个......

$(img).load = function() {
    var $this = $(this);
    width = $this.width();
    height = $this.height();
}

答案 3 :(得分:0)

我不确定为什么原始方法(在很多例子中有效)在这里不起作用。所以我在Stackoverflow上找到了来自 GregL 的一些很棒的代码。

基本上,该方法将新的隐藏图像加载到正文中,然后在删除之前捕获宽度和高度。

$('.postbody').find('img').each(function() {
    var img = $(this), width, height,
        hiddenImg = img.clone().css('visibility', 'hidden').removeAttr('height').removeAttr('width').appendTo('body');
    width = hiddenImg.height();
    height = hiddenImg.width();
    hiddenImg.remove();       
    console.log('Width: '+width+' Height: '+height);
});

Check out the Fiddle