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

标签 javascript jquery

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

基本上,我需要图像的完整尺寸来证明是否应该通过单击事件将其加载到灯箱中。

更新 我现在可以从该函数获取控制台反馈,但它没有为我提供图像的尺寸。

$('.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 函数内部。 我希望它对您有所帮助,如果您有任何其他问题,请随时发表评论:-)

关于javascript - 在收集的 dom 元素上使用 jquery 获取图像的真实尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680418/

相关文章:

javascript - 不使用 HTML 表单通过 ajax POST 上传图片

javascript - 如何禁用整个项目的 ESLint jsx-a11y/alt-text

javascript - 如何修改此代码以在 ES6 中启用尾调用优化?

javascript - ExtJS 主题修改 Ext.panel.Panel

javascript - Jquery AJAX 调用不完整但 JS 语句允许继续?

javascript - 在不触发滚动条的情况下使用 css 和 jquery 将 div 滑出?

javascript - 在更改 BoostrapTable X-可编辑选择框时获取文本而不是值

javascript - 需要 Selenium IDE 中逗号分隔值的数字

javascript - jquery计算选中复选框旁边的html值

javascript - 如何进行模态转换?