是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?
当前回答
如果你正在使用Angular/jQuery,那么这可能会有帮助……
<img ng-src="{{item.url}}" altSrc="{{item.alt_url}}" onerror="this.src = $(this).attr('altSrc')">
解释
假设该项目有一个属性url可能为空,当它是,那么图像将显示为破碎。这将触发onerror属性表达式的执行,如上所述。你需要像上面描述的那样重写src属性,但是你需要jQuery来访问你的altSrc。无法让它与普通JavaScript一起工作。
可能看起来有点俗气,但挽救了我的项目。
其他回答
这对我来说很有效。也许你想用JQuery来挂钩事件。
<img src="foo.jpg" onerror="if (this.src != 'error.jpg') this.src = 'error.jpg';" alt="add alternative text here">
更新了jacquargs错误保护
更新:CSS唯一的解决方案 我最近看到Vitaly Friedman演示了一个我不知道的很棒的CSS解决方案。其思想是将内容属性应用于破碎的图像。通常:after或:before不应用于图像,但当它们被破坏时,它们就会被应用。
<img src="nothere.jpg" alt="add alternative text here">
<style>
img:before {
content: ' ';
display: block;
position: absolute;
height: 50px;
width: 50px;
background-image: url(ishere.jpg);
}
</style>
演示:https://jsfiddle.net/uz2gmh2k/2/
正如提琴所示,破碎的图像本身并没有被删除,但这可能会解决大多数情况下没有任何JS或CSS的问题。如果你需要在不同的位置应用不同的图像,只需用一个类进行区分:.my-special-case img:before{…
上面的解决方案是不完整的,它错过了属性src。
这一点。src和this.attribute('src')是不一样的,第一个包含了对图像的完整引用,例如http://my.host/error.jpg,但属性只是保持原始值error.jpg
正确的解决方案
<img src="foo.jpg" onerror="if (this.src != 'error.jpg' && this.attribute('src') != 'error.jpg') this.src = 'error.jpg';" />
如果你使用的是Angular 1。X你可以包含一个指令,允许你回退到任意数量的图像。fallback属性支持单个url,数组内的多个url,或使用范围数据的角表达式:
<img ng-src="myFirstImage.png" fallback="'fallback1.png'" />
<img ng-src="myFirstImage.png" fallback="['fallback1.png', 'fallback2.png']" />
<img ng-src="myFirstImage.png" fallback="myData.arrayOfImagesToFallbackTo" />
在angular app模块中添加一个新的fallback指令:
angular.module('app.services', [])
.directive('fallback', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var errorCount = 0;
// Hook the image element error event
angular.element(element).bind('error', function (err) {
var expressionFunc = $parse(attrs.fallback),
expressionResult,
imageUrl;
expressionResult = expressionFunc(scope);
if (typeof expressionResult === 'string') {
// The expression result is a string, use it as a url
imageUrl = expressionResult;
} else if (typeof expressionResult === 'object' && expressionResult instanceof Array) {
// The expression result is an array, grab an item from the array
// and use that as the image url
imageUrl = expressionResult[errorCount];
}
// Increment the error count so we can keep track
// of how many images we have tried
errorCount++;
angular.element(element).attr('src', imageUrl);
});
}
};
}])
JQuery的可模块化版本,在文件末尾添加:
<script>
$(function() {
$('img[data-src-error]').error(function() {
var o = $(this);
var errorSrc = o.attr('data-src-error');
if (o.attr('src') != errorSrc) {
o.attr('src', errorSrc);
}
});
});
</script>
在你的img标签上:
<img src="..." data-src-error="..." />
反应
<img
src="https://example.com/does_not_exist.png"
onError={(e) => {
e.currentTarget.src = "https://example.com/default.png"
}}
/>