是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?
当前回答
更新:2022年(chrome仍然工作!!)
我最近不得不构建一个包括任意数量的备份映像的备份系统。下面是我如何使用一个简单的JavaScript函数做到这一点。
HTML
<img src="some_image.tiff"
onerror="fallBackImg(this);"
data-src-1="some_image.png"
data-src-2="another_image.jpg">
JavaScript
function fallBackImg(elem){
elem.error = null;
let index = elem.dataset.fallIndex || 1;
elem.src = elem.dataset[`src-${index}`];
elem.dataset.fallIndex = ++index;
}
我觉得这是处理许多备用图像的一种非常轻量级的方式。
如果你想要“HTML only”,那么这个
<img src="some_image.tiff"
onerror="this.error = null;
let i = this.dataset.i || 1;
this.src = this.dataset[`src-${i}`];
this.dataset.i = ++i;"
data-src-1="some_image.png"
data-src-2="another_image.jpg">
其他回答
上面的解决方案是不完整的,它错过了属性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);
});
}
};
}])
好了! ! 我发现这种方法很方便,检查图像的高度属性为0,然后你可以用默认的图像覆盖src属性: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
image.setAttribute('src','../icons/<some_image>.png');
//check the height attribute.. if image is available then by default it will
//be 100 else 0
if(image.height == 0){
image.setAttribute('src','../icons/default.png');
}
如果你已经创建了动态Web项目,并将所需的图像放置在WebContent中,那么你可以通过使用下面提到的Spring MVC中的代码来访问图像:
<img src="Refresh.png" alt="Refresh" height="50" width="50">
你也可以创建名为img的文件夹,并将图像放在img文件夹中,然后将img文件夹放在WebContent中,然后你可以使用下面提到的代码访问图像:
<img src="img/Refresh.png" alt="Refresh" height="50" width="50">
对于任何图像,只需使用以下javascript代码:
if (ptImage.naturalWidth == 0)
ptImage.src = '../../../../icons/blank.png';
其中ptImage是由document.getElementById()获得的<img>标记地址。