CSS或Javascript - 如果背景图片未加载,则显示后备文字 [英] CSS or Javascript - display fallback text if background image not loaded

查看:783
本文介绍了CSS或Javascript - 如果背景图片未加载,则显示后备文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果徽标图形文件未加载或丢失,如何显示文本而不是徽标?我有背景PNG图片的div:

How can I display text instead of logo, if the logo graphic file isn't loaded or missing? I have div with background PNG image:

<div class="iHaveBgImage">
this text should be displayed if bg image is not loaded
</div>

.iHaveBgImage { background-image: url('img.png') }

它不一定是纯CSS,允许Javascript解决方案。我在想错误事件,但它适用于图像,而不是具有图像背景的元素。

It doesn't have to be pure CSS, Javascript solution is allowed. I was thinking of onerror event, but it works with images, not elements that have image backgrounds.

编辑:
我被告知这个已经回答了,但还有另一种情况。我没有说可以改变DOM,只适用于CSS和JS。第二,在其他解决方案是sugested我应该使用title属性,我试过它,它不显示文本,只徘徊它。

I was told this has been answered before, but there is another situation. I didn't say one can alter DOM, only apply CSS and JS. Second, in that other solution is sugested I should use title attribute and I tried it and it doesn't display text, only hovers it.

推荐答案

尝试这样:

HTML

<div class="iHaveBgImage">
  <p>this text should be displayed if bg image is not loaded</p>
</div>

CSS

.iHaveBgImage { background-image:
url('https://s31.postimg.org/yqv51r5xn/6936671_hd_wallpapers_for_ipad.jpg');
color:red;
}

.iHaveBgImage > p {
  position: relative;
  z-index: -1;
}

工作得很好 https://jsfiddle.net/s0gt2eng/

这篇关于CSS或Javascript - 如果背景图片未加载,则显示后备文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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