我如何隐藏破碎的图像图标? 例子:
我有一个图像与错误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">
其他回答
在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中添加边界只是为了演示图像的位置。
如果你将添加alt与文本alt="abc",它将显示显示腐败缩略图,和alt消息abc
<img src="pic_trulli.jpg" alt="abc"/>
如果你不添加alt,它将显示显示腐败缩略图
<img src="pic_trulli.jpg"/>
如果你想把坏掉的藏起来 只需添加alt=""它将不会显示损坏的缩略图和任何alt消息(不使用js)
<img src="pic_trulli.jpg" alt=""/>
如果你想把坏掉的藏起来 只需添加alt="" & onerror="this.style。Display ='none'"它不会显示损坏的缩略图和任何Alt消息(与js)
<img src="pic_trulli.jpg" alt="abc" onerror="this.style.display='none'"/>
第四个有点危险(不完全是) ,如果你想在onerror事件中添加任何图像,即使image作为样式存在,它也不会显示。显示就像加法。因此,当您不需要任何替代图像显示时使用它。
display: 'none'; // in css
如果我们在CSS中给出它,那么项目将不会显示(像image, iframe, div之类的)。
如果你想显示图像&你想显示完全空白,如果错误,那么你可以使用,但也要小心,这不会占用任何空间。所以,你需要把它保存在一个div中
链接https://jsfiddle.net/02d9yshw/
我将以别人的答案为基础。而不是隐藏标签(可能有重要的样式),给它一个虚拟的图像:
<img src="nonexistent.png" onerror="this.src=`data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg'></svg>`;"/>
缺失的图像要么什么都不显示,要么显示一个[?]样式框,当无法找到它们的源时。相反,你可能想用一个你确定存在的“缺失的图像”图形来替换它,这样就有更好的视觉反馈,表明有问题。或者,你可能想把它完全隐藏起来。这是可能的,因为浏览器无法找到的图像会触发我们可以观察的“错误”JavaScript事件。
//Replace source
$('img').error(function(){
$(this).attr('src', 'missing.png');
});
//Or, hide them
$("img").error(function(){
$(this).hide();
});
此外,当发生这种情况时,您可能希望触发某种Ajax操作,向站点管理员发送电子邮件。