是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?


当前回答

在Spring in Action第三版中找到了这个解决方案。

<img src=“../资源/images/Image1.jpg”

更新: 这不是一个只有HTML的解决方案…Onerror是javascript

其他回答

如果你已经创建了动态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">
<style type="text/css">
img {
   background-image: url('/images/default.png')
}
</style>

请务必输入图像的尺寸,以及是否希望图像平铺。

我认为仅仅使用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;
        }
    }
}

像这样使用它:

 window.onload = function() {
    fixBrokenImages('example.com/image.png');
 }

在Chrome和Firefox中测试

好了! ! 我发现这种方法很方便,检查图像的高度属性为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');
  }

3个解决方案:


考虑以下html文件:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
   <title>Document</title>
</head>
<body>
   <img id="imageId">
   <script src="setimage.js"></script>
</body>
</html>

解决方案一: 在html的body标签中引用这段JS代码为 < script src = " setimage.js " > < /脚本> 并设置SRC路径,第一个是如果有错误,下一个是你希望第一次工作的路径:)

var img = document.getElementById("imageId")
       img.onerror = () => {
           img.src= "../error.png";
       }
       img.src= "../correct.webp.png";

解决方案二:

这个解决方案几乎是相同的,相反,您将调用方法,同样是在脚本标记的正文的末尾,但将在那里提供路径。

function setImageWithFallback(mainImgPath, secondaryImgPath) {
   var img = document.getElementById("imageId")
       img.onerror = () => {
           img.src= mainImgPath;
       }
       img.src= secondaryImgPath;
}

解决方案三: 如果它只是一张图片,这将是最简单的:)只是在img标签上设置onerror

<img id="imageId" src="../correct.webp.png" 
onerror="if (this.src != '../error.png') this.src = '../error.png';">