我在HTML页面中有一张图片:
<img src="smiley.gif" alt="Smiley face" width="32" height="32" />
如果在服务器上找不到该图像,则会显示一个难看的空白方块。
我要这样做,以便如果找不到图像,它将什么也不显示,或者我知道肯定在服务器上的其他一些默认图像。
如何才能做到这一点?
我在HTML页面中有一张图片:
<img src="smiley.gif" alt="Smiley face" width="32" height="32" />
如果在服务器上找不到该图像,则会显示一个难看的空白方块。
我要这样做,以便如果找不到图像,它将什么也不显示,或者我知道肯定在服务器上的其他一些默认图像。
如何才能做到这一点?
Answers:
解决问题的最佳方法:
<img id="currentPhoto" src="SomeImage.jpg" onerror="this.onerror=null; this.src='Default.jpg'" alt="" width="100" height="120">
onerror 对你来说是一件好事:)
只需更改图像文件名即可尝试。
if (this.src != 'Default.jpg')
this.onerror=null;@Sudarshan在下面提供的if:更好。
好的,但是我喜欢使用这种方式,这样每当原始图像不可用时,您都可以加载默认图像,该图像可能是您最喜欢的笑脸或说对不起的图像!不可用,但是如果两个图像都丢失,则可以使用文本显示。在那里你也可以笑脸。看看几乎涵盖所有情况。
<img src="path_to_original_img/img.png" alt="Sorry! Image not available at this time"
onError="this.onerror=null;this.src='<?=base_url()?>assets1/img/default.jpg';">
<?=base_url()?>办?为什么您惊讶地添加一些服务器端和基于框架的代码?
在这里检查下面的代码片段,在这个代码片段中,我拼错了图像名称。因此,正因为如此,它会将替代图像显示为未找到图像(404.svg)。
<img id="currentPhoto" src="https://www.ccrharrow.org/Images/content/953/741209.pg" onerror="this.src='https://www.unesale.com/ProductImages/Large/notfound.png'" alt="">
您可以通过添加显示替代文本alt:
<img src="my_img.png" alt="alternative text" border="0" />
我在图像周围添加了一个父div,并使用以下onerror事件处理程序隐藏了原始图像,因为在IE中使用alt属性后,仍然显示了一个丑陋的图像未找到的图像:
<div style=" width:300px; height:150px; float:left; margin-left:5px; margin-top:50px;">
<img src='@Url.Content("~/Images/Logo-Left.png")' onerror="this.parentElement.innerHTML = '';" />
</div>
尝试border=0在img标签中使用,以使丑陋的正方形消失。
<img src="someimage.png" border="0" alt="some alternate text" />
我想隐藏<img>标签占用的空间,所以这对我有用
<img src = "source.jpg" alt = "" >
它对我有用,如果您不想在图像中断时使用alt属性,则可以使用这段代码并进行相应设置。
<h1>
<a>
<object data="~/img/Logo.jpg" type="image/png">
Your Custom Text Here
</object>
</a>
</h1>
解决方案-我删除了img的height和width元素,然后替换文本起作用。
<img src="smiley.gif" alt="Smiley face" width="32" height="32" />
至
<img src="smiley.gif" alt="Smiley face" />
谢谢你们。