我如何隐藏破碎的图像图标? 例子:
我有一个图像与错误src:
<img src="Error.src"/>
该解决方案必须适用于所有浏览器。
我如何隐藏破碎的图像图标? 例子:
我有一个图像与错误src:
<img src="Error.src"/>
该解决方案必须适用于所有浏览器。
当前回答
在https://bitsofco.de/styling-broken-images/找到了一个很好的解决方案
img { position: relative; } /* style this to fit your needs */ /* and remove [alt] to apply to all images*/ img[alt]:after { display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #fff; font-family: 'Helvetica'; font-weight: 300; line-height: 2; text-align: center; content: attr(alt); } <img src="error"> <br> <img src="broken" alt="A broken image"> <br> <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">
其他回答
只使用CSS是很困难的,但是你可以使用CSS的background-image而不是<img>标签…
就像这样:
HTML
<div id="image"></div>
CSS
#image {
background-image: url(Error.src);
width: //width of image;
height: //height of image;
}
这是一把能用的小提琴。
注意:我在CSS中添加边界只是为了演示图像的位置。
在https://bitsofco.de/styling-broken-images/找到了一个很好的解决方案
img { position: relative; } /* style this to fit your needs */ /* and remove [alt] to apply to all images*/ img[alt]:after { display: block; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #fff; font-family: 'Helvetica'; font-weight: 300; line-height: 2; text-align: center; content: attr(alt); } <img src="error"> <br> <img src="broken" alt="A broken image"> <br> <img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">
我将以别人的答案为基础。而不是隐藏标签(可能有重要的样式),给它一个虚拟的图像:
<img src="nonexistent.png" onerror="this.src=`data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>`;"/>
我喜欢尼克的答案,并一直在研究这个解决方案。找到了一个更干净的方法。由于::before/::after伪元素不能用于替换的元素,如img和object,它们只在对象数据(src)未加载时才会工作。它使HTML更加清晰,并且只在对象加载失败时才添加pseudo。
对象{ 位置:相对; 浮:左; 显示:块; 宽度:200 px; 身高:200 px; margin-right: 20 px; 边框:1px纯黑色; } 对象::{后 位置:绝对的; 上图:0; 左:0; 显示:块; 宽度:100%; 高度:100%; 内容:”; 背景:红色url(“http://placehold.it/200x200”); } <object data="http://lorempixel.com/200/200/people/1" type="image/png"></object> . <对象数据= " http://broken。img / url " type = " / png图像“> < /对象>
其他人所描述的同样的想法在React中工作如下:
<img src='YOUR-URL' onError={(e) => e.target.style.display='none' }/>