是否有任何方法在HTML <img>标记中呈现默认图像,以防src属性无效(仅使用HTML)?如果不是,你会用什么轻量级的方式来解决这个问题?
当前回答
<style type="text/css">
img {
background-image: url('/images/default.png')
}
</style>
请务必输入图像的尺寸,以及是否希望图像平铺。
其他回答
简单利落的解决方案,包括一些好的答案和评论。
<img src="foo.jpg" onerror="this.src='error.jpg';this.onerror='';">
它甚至解决了无限循环风险。
为我工作。
<img style=“background-image: url(image1), url(image2);”></img>
使用背景图像,让您可以添加多个图像。 我的情况: Image1是主图像,这将从某个地方获取(浏览器执行请求) Image2是加载image1时显示的默认本地图像。 如果image1返回任何类型的错误,用户将看不到任何更改,这对于用户体验来说是干净的
<style type="text/css">
img {
background-image: url('/images/default.png')
}
</style>
请务必输入图像的尺寸,以及是否希望图像平铺。
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';">
好了! ! 我发现这种方法很方便,检查图像的高度属性为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');
}
推荐文章
- 使伸缩项目正确浮动
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?
- 如何删除和清除所有的本地存储数据
- 强制打开“另存为…”弹出打开文本链接点击PDF在HTML
- 如何修改标签文本?
- 在HTML中还有其他有用的空格码吗,比如半空格的 , em-spaces, en-spaces等等?
- 输入触发器按钮单击