jquery:domready 或加载时的图像宽度?
嘿伙计们, 我正在使用 jquery data() 方法来存储图像的宽度。
jquery什么时候可以获取图片的宽度? on-dom-ready 还是 on-load? 是否需要加载图像来查询其宽度,或者我也可以在 domready 上查询宽度吗?
谢谢
这是我的一段代码:
//Save the original image width
$(".post-body img").each(function() {
$(this).data('width', $(this).width());
});
hey guys,
I'm using the jquery data() method to store the width of images.
When is jquery able to get the width of images. on-dom-ready or on-load?
Is it necessary to have the images loaded to query it's width, or can i query the width on domready as well?
thank you
this is my piece of code:
//Save the original image width
$(".post-body img").each(function() {
$(this).data('width', $(this).width());
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于,如果您指定宽度,那么 DOM Ready 就可以正常工作。如果您依赖于图像本身的宽度,则需要在加载图像后进行检查,使用在图像加载后触发的
window.onload
,例如:It depends, if you're specifying the width, then DOM ready works fine. If you're depending on the width coming from the image itself, you need to check once it's loaded, using
window.onload
which fires after images are loaded, for example:如果页面加载时所有图像都会进入,并且您确定之后不会加载任何图像(由于 ajax 调用或其他原因),尼克的答案会很好。不然的话,难度就有点大了。这是我在这种情况下为图像加载事件绑定的事件:
https: //github.com/peol/jquery.imgloaded/pull/4#diff-0
这仍然是一项正在进行的工作,因为这是一个棘手的问题......
If all of your images are coming in when the page loads and you are sure that none are going to be loaded after (as a result of ajax calls or something) Nick's answer will work fine. Otherwise, it is a bit tougher. Here is the event I bind to for image load event for such cases:
https://github.com/peol/jquery.imgloaded/pull/4#diff-0
It's still a work in progress since this is a tough problem...