使用背景的 onerror 事件:url() [英] onerror event using background: url()
问题描述
如果找不到源图像,有没有办法显示替代图像?我知道要做到这一点是通过执行以下操作:
<img src="imagenotfound.gif" alt="图片未找到" onError="this.src='imagefound.gif';"/>
但是如果你在做这样的事情,如果有错误或者没有找到图像,你怎么能捕捉到呢?
<div style="background:url('myimage.gif')"></div>
如果 myimage.gif
不透明,你可以使用多个背景:
背景:url('myimage.gif'), url('fallback.gif');
这样 fallback.gif
只有在 myimage.gif
不可用时才可见.
请注意,即使 myimage.gif
可用,也可以下载 fallback.gif
.
另外,即使没有得到广泛支持,CSS Images 3 也引入了 image()
符号:
background: image('myimage.gif', 'fallback.gif');
<块引用>
多个<image-decl>s
可以用逗号分隔,在在这种情况下,函数代表第一个不是无效图片.
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>
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.
这篇关于使用背景的 onerror 事件:url()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!