使用背景的onerror事件:url() [英] onerror event using background: url()

查看:382
本文介绍了使用背景的onerror事件:url()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果找不到源图像,是否可以显示替代图像?我知道要做到这一点是通过执行以下操作:

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>

推荐答案

如果myimage.gif不透明,则可以使用多个背景:

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

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

只有当myimage.gif不可用时,这种方式fallback.gif才可见.

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

请注意,即使myimage.gif可用,也可能会下载fallback.gif.

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

或者,即使不受广泛支持,CSS Images 3也引入了 image()标记:

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

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

可以使用逗号分隔多个 <image-decl>s . 在这种情况下,该函数表示的不是 无效的图像.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆