我正在尝试获取页面上图像的尺寸,以便进一步与自定义“灯箱”或排序一起使用。但是,当尝试纯 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 步中设置的函数运行并设置变量。
因此,使用宽度和高度的代码应该位于 image.load 函数内部。 我希望它对您有所帮助,如果您有任何其他问题,请随时发表评论:-)
关于javascript - 在收集的 dom 元素上使用 jquery 获取图像的真实尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26680418/