在收集的dom元素上使用jquery获取图像的真实维度
Getting true dimensions of images with jquery on collected dom elements
我正在尝试获取页面上图像的尺寸,以便进一步与自定义的"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中设置的函数运行并设置可变值
因此,使用宽度和高度的代码应该位于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
相关文章:
- 在for循环中未获取JQuery/JavaScript对象值
- 点击获取jQuery上的href属性
- 如何获取jQuery Confirm(jConfirm)值并使用该值检查条件
- 通过传递的参数位置获取jQuery中图像的宽度
- MVC Syncfusion Grid-HTML EJ Grid-获取Jquery中所选行的主键
- 如何获取 jQuery 以触发本机自定义事件处理程序
- 如何获取 jQuery 回调触发返回值
- 如何在wordpress插件中获取jquery中的img url和文件url
- 我想知道如何只激活表单提交,而不获取jquery中ajax url的值
- 如何获取jQuery集合中的第k个元素..作为JQUERY元素
- 从aspx.cs页面获取jquery post中的Null响应而不是json
- 如何获取 jquery 变量 childeren
- 如何从每个对象获取jQuery的“title”和“url”值
- 如何动态获取jquery noConflict()的引用
- 用于获取jQuery元素或值的方法
- 获取jquery数组对象的第n项
- 获取jquery确认在函数中返回的结果
- 获取JQuery UI自动完成元素的索引
- 获取jQuery UI排序后的ID数组
- 获取 jQuery DataTable 中的元素