输入默认图像以防 html <img> 的 src 属性无效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/980855/
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
Inputting a default image in case the src attribute of an html <img> is not valid?
提问by Galilyou
Is there any way to render a default image in an HTML <img>
tag, in case the src
attribute is invalid (using only HTML)? If not, what would be your lightweight way to work around it?
有没有办法在 HTML<img>
标签中呈现默认图像,以防src
属性无效(仅使用 HTML)?如果没有,您的轻量级解决方法是什么?
回答by Patrick McElhaney
You asked for an HTML onlysolution...
您要求仅提供HTML解决方案...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Object Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<p>
<object data="http://stackoverflow.com/does-not-exist.png" type="image/png">
<img src="https://cdn.sstatic.net/Img/unified/sprites.svg?v=e5e58ae7df45" alt="Stack Overflow logo and icons and such">
</object>
</p>
</body>
</html>
Since the first image doesn't exist, the fallback (the sprites used on this web site*) will display. And if you're using a reallyold browser that doesn't support object
, it will just ignore that tag and use the img
tag. See caniusewebsite for compatibility. As of 2018 this element is widely supported by any and all browsers from ie6+.
由于第一个图像不存在,后备(本网站上使用的精灵*)将显示。如果您使用的是不支持的非常旧的浏览器object
,它只会忽略该标签并使用该img
标签。有关兼容性,请参阅caniuse网站。截至 2018 年,该元素已被 ie6+ 的所有浏览器广泛支持。
* Unless the URL for the image changed (again), in which case you'll probably see the alt text.
* 除非图像的 URL 更改(再次),在这种情况下您可能会看到替代文本。
回答by Svend
This works well for me. Maybe you wanna use JQuery to hook the event.
这对我很有效。也许您想使用 JQuery 来挂钩事件。
<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';">
Updated with jacquargs error guard
更新了 jaquargs 错误防护
Updated: CSS only solutionI recently saw Vitaly Friedmandemo a great CSS solution I wasn't aware of. The idea is to apply the content
property to the broken image. Normally :after
or :before
do not apply to images, but when they're broken, they're applied.
更新:仅 CSS 解决方案我最近看到Vitaly Friedman演示了一个我不知道的出色 CSS 解决方案。这个想法是将content
属性应用于损坏的图像。通常:after
或:before
不适用于图像,但是当它们损坏时,它们会被应用。
<img src="nothere.jpg">
<style>
img:before {
content: ' ';
display: block;
position: absolute;
height: 50px;
width: 50px;
background-image: url(ishere.jpg);
</style>
Demo: https://jsfiddle.net/uz2gmh2k/2/
演示:https: //jsfiddle.net/uz2gmh2k/2/
As the fiddle shows, the broken image itself is not removed, but this will probably solve the problem for most cases without any JS nor gobs of CSS. If you need to apply different images in different locations, simply differentiate with a class: .my-special-case img:before { ...
正如小提琴所示,损坏的图像本身不会被删除,但这可能会解决大多数情况下没有任何 JS 或 CSS 的问题。如果需要在不同的位置应用不同的图像,只需用一个类来区分:.my-special-case img:before { ...
回答by amit bakle
Found this solution in Spring in Action 3rd Ed.
在 Spring in Action 3rd Ed 中找到了这个解决方案。
<img src="../resources/images/Image1.jpg" onerror="this.src='../resources/images/none.jpg'" />
<img src="../resources/images/Image1.jpg" onerror="this.src='../resources/images/none.jpg'" />
Update:This is not an HTML only solution... onerror
is javascript
更新:这不是仅 HTML 的解决方案......onerror
是 javascript
回答by Emiliano Barboza
<img style="background-image: url(image1), url(image2);"></img>
Use background image that let you add multiple images. My case: image1 is the main image, this will get from some place (browser doing a request) image2 is a default local image to show while image1 is being loaded. If image1 returns any kind of error, the user won't see any change and this will be clean for user experience
使用可让您添加多个图像的背景图像。我的情况:image1 是主图像,这将从某个地方获取(浏览器执行请求) image2 是在加载 image1 时显示的默认本地图像。如果 image1 返回任何类型的错误,用户将看不到任何更改,这对于用户体验来说是干净的
回答by lambacck
<style type="text/css">
img {
background-image: url('/images/default.png')
}
</style>
Be sure to enter dimensions of image and whether you want the image to tile or not.
请务必输入图像的尺寸以及是否要平铺图像。
回答by Pim Jager
I don't think it is possible using just HTML. However using javascript this should be doable. Bassicly we loop over each image, test if it is complete and if it's naturalWidth is zero then that means that it not found. Here is the code:
我认为仅使用 HTML 是不可能的。但是使用 javascript 这应该是可行的。基本上我们遍历每个图像,测试它是否完整,如果它的 naturalWidth 为零,那么这意味着它没有找到。这是代码:
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
Use it like this:
像这样使用它:
window.onload = function() {
fixBrokenImages('example.com/image.png');
}
Tested in Chrome and Firefox
在 Chrome 和 Firefox 中测试
回答by Obie
If you're using Angular/jQuery then this might help...
如果您使用的是 Angular/jQuery,那么这可能会有所帮助...
<img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">
Explanation
解释
Assuming that item
has a property url
that might be null, when it is then the image will show up as broken. That triggers execution of onerror
attribute expression, as described above. You need to override the src
attribute as described above, but you will need jQuery to access your altSrc. Couldn't get it to work with vanilla JavaScript.
假设它item
有一个url
可能为空的属性,那么图像将显示为已损坏。onerror
如上所述,这会触发属性表达式的执行。您需要src
如上所述覆盖该属性,但您将需要 jQuery 来访问您的 altSrc。无法让它与 vanilla JavaScript 一起工作。
Might seem a little hacky but saved the day on my project.
可能看起来有点笨拙,但在我的项目中挽救了这一天。
回答by bapho
a simple img-element is not very flexible so i combined it with a picture-element. this way no CSS is needed. when an error occurs, all srcset's are set to the fallback version. a broken link image is not showing up. it does not load unneeded image versions. the picture-element supports responsive design and multiple fallbacks for types that are not supported by the browser.
一个简单的 img 元素不是很灵活,所以我将它与图片元素结合起来。这样就不需要CSS了。发生错误时,所有 srcset 都设置为回退版本。断开的链接图像未显示。它不会加载不需要的图像版本。图片元素支持响应式设计和浏览器不支持的类型的多种回退。
<picture>
<source id="s1" srcset="image1_not_supported_by_browser.webp" type="image/webp">
<source id="s2" srcset="image2_broken_link.png" type="image/png">
<img src="image3_fallback.jpg" alt="" onerror="this.onerror=null;document.getElementById('s1').srcset=document.getElementById('s2').srcset=this.src;">
</picture>
回答by user3601578
angular2:
角度2:
<img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">
回答by eithed
An HTML only solution, where the only requirement is that you knowthe size of the image that you're inserting. Will not work for transparent images, as it uses background-image
as a filler.
仅 HTML 的解决方案,其中唯一的要求是您知道要插入的图像的大小。不适用于透明图像,因为它background-image
用作填充物。
We can successfully use background-image
to link the image that appears if the given image is missing. Then the only problem is the broken icon image - we can remove it by inserting a very big empty character, thus pushing the content outside the display of img
.
background-image
如果给定的图像丢失,我们可以成功地使用链接出现的图像。然后唯一的问题是损坏的图标图像 - 我们可以通过插入一个非常大的空字符来删除它,从而将内容推到img
.
img {
background-image: url("http://placehold.it/200x200");
overflow: hidden;
}
img:before {
content: " ";
font-size: 1000px;
}
This image is missing:
<img src="a.jpg" style="width: 200px; height: 200px"/><br/>
And is displaying the placeholder
An CSS only solution (Webkit only)
仅限 CSS 的解决方案(仅限 Webkit)
img:before {
content: " ";
font-size: 1000px;
background-image: url("http://placehold.it/200x200");
display: block;
width: 200px;
height: 200px;
position: relative;
z-index: 0;
margin-bottom: -16px;
}
This image is there:
<img src="http://placehold.it/100x100"/><br/>
This image is missing:
<img src="a.jpg"/><br/>
And is displaying the placeholder