如果未找到原始图像,如何在 HTML 中制作占位符图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32909488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 18:18:33  来源:igfitidea点击:

How do I make a placeholder image in HTML if the original image hasn't been found?

htmlcss

提问by StevoHN

Basically what the title says.

基本上就是标题所说的。

I'm making an html page, and using images for link. But can I make it so the images show a default icon if the specified file hasn't been found?

我正在制作一个 html 页面,并使用图像作为链接。但是,如果未找到指定的文件,我可以使图像显示默认图标吗?

回答by x13

You'll have to use javascript:

你必须使用javascript:

<img src="404image" onerror="this.src='images/not_found.png';" />

回答by Richard Parnaby-King

If you specify the width and height of an image in the css, you can set the background image as a not-found image:

如果在css中指定了图片的宽高,可以将背景图片设置为未找到图片:

img {
  width:100px;
  height:100px;
  background: url(http://goo.gl/vyAs27) no-repeat scroll 0 0;
}
<img src="not-found.png" /><img src="http://goo.gl/ijai22" />

Most browsers will insert an image missing icon in the corner. There's no way that I know of to remove this.

大多数浏览器会在角落插入一个图像缺失图标。我知道没有办法删除它。

As you can see, your regular image will overlay the background image.

如您所见,您的常规图像将覆盖背景图像。

If your image has a transparent background then the background image will be visible behind the loaded image.

如果您的图像具有透明背景,则背景图像将在加载的图像后面可见。

Alternatively, use a server-side programming language that checks if the image exists. If it does not, load a placeholder...

或者,使用服务器端编程语言来检查图像是否存在。如果没有,请加载占位符...

回答by Swaps

If you just want to display a blank space without any dummy image/caption, remove the alt option that you have specified in the imgtag.

如果您只想显示一个没有任何虚拟图像/标题的空白区域,请删除您在img标签中指定的 alt 选项。

<img src='not_found.jpg' alt='' class=''>

Here the source not_found.jpgis the wrong path which won't give any image. PFA for sample o/p.

这里的来源not_found.jpg是错误的路径,不会给出任何图像。样品 o/p 的 PFA。

  • Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.
  • 这里第一张图像显示何时获得有效的 src,第二张图像显示没有任何标题的空白区域。

Here 1st image is showing when it gets valid src & the 2nd one shows the blank space without any caption.

这里第一张图像显示何时获得有效的 src,第二张图像显示没有任何标题的空白区域。

回答by HAPPY SINGH

Set images resolution what you need. for example, I need image size: 100X100. put live of image path or set proper path of an image source for your folder.

设置您需要的图像分辨率。例如,我需要图像大小:100X100。放置图像路径或为您的文件夹设置图像源的正确路径。

CSS:

CSS:

img {
   width:100px;
   height:100px;
}

HTML:

HTML:

<img src="https://dummyimage.com/100/00ff48/ff0000.png&text=Image+Found" alt="not found image" />