CSS 或 Javascript - 如果未加载背景图像则显示回退文本

CSS or Javascript - display fallback text if background image not loaded

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

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

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

不必是纯粹的CSS,Javascript解是允许的。我在考虑 onerror 事件,但它适用于图像,而不是具有图像背景的元素。

编辑: 有人告诉我这已经被回答过,但还有另一种情况。我没说可以改DOM,只适用CSS和JS。其次,在建议的其他解决方案中,我应该使用 title 属性,我试过了,它不显示文本,只将其悬停。

一个解决方法是更改​​

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

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

收件人:

<img src="img.png" alt="Seems like this image failed to load" />

或者我不确定以下是否可行,但您可以按照以下方式做一些事情:

<img class="iHaveBgImage" alt="Seems like this image failed to load" />

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

编辑: 我脑子里突然冒出的可能也有用的东西是:

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

.iHaveBgImage { 
background-image: url('img.png') 
}
.bgText {
  z-index: -9999;
}

试试这个

P.hidden {
    visibility: hidden;
}
.iHaveBgImage {
  background-image: url('https://s31.postimg.org/yqv51r5xn/6936671_hd_wallpapers_for_ipad.jpg');
  color: red;
width:700px;
  height:300px;
}
<div class="iHaveBgImage">
   <p class="hidden> This text should be displayed if bg image is not loaded</p>
</div>

如果您想使用文本可见的文本,请使用 <span></span> 标签并创建 css span {display: block;}

html

 <p class="hidden> This text should be displayed if bg image is not loaded</p>

CSS

P.hidden {
    visibility: hidden;
}

这是我在duplicate tag中建议的:

.iHaveBgImage{
  width:500px;
  height:200px;
  background-image: url('http://www.menucool.com/slider/jsImgSlider/images/image-slider-5.jpg');
  }
<div class="iHaveBgImage" title="this text should be displayed if bg image is not loaded">
</div>

使用 span 标签的替代方法:

span.image:before{
  content:" "; background:url('http://www.menucool.com/slider/jsImgSlider/images/image-slider-5.jpg');
  display: block;
  position:absolute;
  width:500px;
  height:200px;
}
  <span class="image">alternate text</span>

这样试试:

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/