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

Getting true dimensions of images with jquery on collected dom elements

本文关键字:获取 jquery 图像 真实 dom 元素      更新时间:2023-09-26

我正在尝试获取页面上图像的尺寸,以便进一步与自定义的"lightbox"或排序一起使用。然而,当同时尝试纯js方法和jquery方法时,我会得到变量的输出undefined。为什么会这样?是因为jquery加载事件吗?我试着既有负荷又有准备。

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

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

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

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

  1. 设置函数以在加载图像时检索宽度和高度
  2. 显示宽度和高度变量(尚未设置)
  3. 步骤1中设置的函数运行并设置可变值

因此,使用宽度和高度的代码应该位于image.load函数内部。我希望它能有所帮助,如果你有任何进一步的问题,请毫不犹豫地评论:-)

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

试试这个。。。

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

我不太清楚为什么原始方法(在很多例子中都有效)在这里不起作用。因此,我在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);
});

查看Fiddle