我正在尝试在页面上获取图像的尺寸,以便进一步使用自定义“灯箱”或排序。但是,在尝试纯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>
答案 0 :(得分:1)
您异步设置变量并直接获取。 在伪代码中它有点像这样:
因此,使用宽度和高度的代码应该在里面 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);
});