Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

html - onerror event using background: 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...