onerror event using background: url()

百般思念 提交于 2019-12-31 08:44:35

问题


Is there a way to show alternate image if source image is not found? I know to accomplish this is by doing something like below:

<img src="imagenotfound.gif" alt="Image not found" onError="this.src='imagefound.gif';" />

But how about if you are doing something like this, how can you catch if there is an error or if the image is not found?

<div style="background:url('myimage.gif')"></div>

回答1:


In case myimage.gif isn't transparent, you could use multiple backgrounds:

background: url('myimage.gif'), url('fallback.gif');

This way fallback.gif will only be visible if myimage.gif isn't available.

Note that fallback.gif may be downloaded even if myimage.gif is available.


Alternatively, even though not widely supported, CSS Images 3 introduces the image() notation:

background: image('myimage.gif', 'fallback.gif');

Multiple <image-decl>s can be given separated by commas, in which case the function represents the first image that's not an invalid image.




回答2:


With background images, there is no event; you have check yourself.

Make an (XML)HTTP request, and if you get a response with an error status code or no response at all (after timeout), use another image resource. This approach is limited by the Same-Origin Policy.




回答3:


You can also use a dummy-image and use the onerror event from there ...

        $imageFoo = '
        <div id="' . $uniqueId . '"
             style="
                background-image: url(//foo.lall/image.png);
                -webkit-background-size: contain;
                -moz-background-size: contain;
                -o-background-size: contain;
                background-size: contain;
                background-position: center;
                background-repeat: no-repeat;
             "
        ></div>
        <!-- this is a helper, only needed because "background-image" did not fire a "onerror" event -->
        <img style="display: none;" 
             src="//foo.lall/image.png" 
             onerror="var fallbackImages = $(this).data(\'404-fallback\'); $(\'#' . $uniqueId . '\').css(\'background-image\', \'url(\' + fallbackImages + \')\');"
             data-404-fallback="//foo.lall/image_fallback.png"
        >
        ';


来源:https://stackoverflow.com/questions/22287474/onerror-event-using-background-url

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