简体   繁体   English

显示一些 HTML 时<img>无法显示(而不是图像)

[英]Displaying some HTML for when an <img> can't be shown (instead of the image)

I happen to have a stylized image with a list inside it in some HTML page.我碰巧在一些 HTML 页面中有一个带有列表的风格化图像。

If the image cannot be shown, I want to have a normal HTML list instead of it (in a similar vein to an alt text, but with HTML tags and not just text).如果无法显示图像,我想要一个普通的 HTML 列表而不是它(与 alt 文本类似,但使用 HTML 标签而不仅仅是文本)。

Is there a best way to do that?有没有最好的方法来做到这一点? (like a CSS rule or something?) (比如 CSS 规则之类的?)

Thanks谢谢

There is a standard way to do this without resorting to JavaScript.有一种标准方法可以做到这一点,而无需求助于 JavaScript。 Use the object element instead of the img element.使用 object 元素代替 img 元素。 If the image can't be displayed, the content of the object element is used.如果无法显示图像,则使用 object 元素的内容。 So:所以:

 <p>When the image displays:</p> <object data="https://via.placeholder.com/50" style="height:50px"> <ul> <li>list item 1</li> <li>list item 2</li> </ul> </object> <p>When the image doesn't display:</p> <object data="https://error.placeholder.com/50" style="height:50px"> <ul> <li>list item 1</li> <li>list item 2</li> </ul> </object>

You can listen for the error event , which fires when the resource can't be loaded:您可以侦听error事件,该事件在资源无法加载时触发:

 function badImage(imageElement){ imageElement.outerHTML = "This image can't be shown" }
 <img src="https://.com" onerror="badImage(this)">

the list is overlaped by the image normaly.该列表通常与图像重叠。 if the image has an error loading, it will become invisible.如果图像加载错误,它将变得不可见。

not 100% sure if it will work though.不是 100% 确定它是否会起作用。

css: css:

img {
  z-index: 1;
  position: absolute;
  top:0px;
  left:0px;
}
ul {
  /*z-index: 0;*/
  position: absolute;
  top:0px;
  left:0px;
}
  

html: html:

<ul>
 <li>item 1</li>
 <li>item 2</li>
 <li>item 3</li>
</ul>

<img src="image.jpg" onerror="document.querySelector('img').style.visibility = "hidden"">

you can style the list however you like.您可以随意设置列表样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM