jquery: image width on domready or load?

强颜欢笑 提交于 2020-01-05 06:28:34

问题


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());
    });

回答1:


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:

$(window).load(function() {
  var w = $("img").width();
});



回答2:


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...



来源:https://stackoverflow.com/questions/4461689/jquery-image-width-on-domready-or-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!