Check if an image is loaded (no errors) with jQuery

前端 未结 15 1345
挽巷
挽巷 2020-11-21 20:45

I\'m using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs

15条回答
  •  后悔当初
    2020-11-21 21:29

    Check the complete and naturalWidth properties, in that order.

    https://stereochro.me/ideas/detecting-broken-images-js

    function IsImageOk(img) {
        // During the onload event, IE correctly identifies any images that
        // weren’t downloaded as not complete. Others should too. Gecko-based
        // browsers act like NS4 in that they report this incorrectly.
        if (!img.complete) {
            return false;
        }
    
        // However, they do have two very useful properties: naturalWidth and
        // naturalHeight. These give the true size of the image. If it failed
        // to load, either of these should be zero.
        if (img.naturalWidth === 0) {
            return false;
        }
    
        // No other way of checking: assume it’s ok.
        return true;
    }
    

提交回复
热议问题