javascript - 如何替换因丢失或错误图像 src 而损坏的 HTML img

标签 javascript html css angular

我有以下代码:

<img src="test.jpg" width="20" height="20"> some content here
当找不到图像时,它显示如下:
enter image description here

This behavior is different according to browsers.


我想显示在所有浏览器中看起来都一样的透明框(纯白色)或一些好看的容器(空框)。我尝试过使用 alt 标签,但它不起作用。
我怎样才能做到这一点?
演示:Sample

<img src="img_girl.jpg" width="20" height="20"> some content here

最佳答案

您可以使用 error onError 的处理程序. 但请务必取消 onError调用后的处理程序 ,因为如果您的备份图像丢失,这将导致服务器请求的无限循环——不好!就这样处理...

<img src="test.jpg" width="20" height="20" onerror="this.onerror=null;this.src='imageNotFound.gif';">
通过设置 this.onerror=null; ,我们正在防止服务器请求的无限循环。然后imageNotFound.gif如果图像在那里,将为用户显示。
POD(来源:MDN Web Docs: GlobalEventHandlers.onerror)....

The reason we have the this.onerror=null in the function is that the browser will be stuck in an endless loop if the onerror image itself generates an error.

关于javascript - 如何替换因丢失或错误图像 src 而损坏的 HTML img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64610101/

相关文章:

html - Angular 动画 ng-cloak 不透明度

css - 对 custom.css.scss 进行微小更改后 Bootstrap 无法正常工作

javascript - 在我的 api 调用中使用对象解构而不是默认参数

html - 点击视频播放 HTML5/CSS3

javascript - 工具提示 jquery 始终存在

css - 弹出式菜单在 Chrome、Opera 和 Safari 中的 flash 下弹出

javascript - Angularjs 选项卡在渲染时加载微调器

javascript - 在手机屏幕关闭的情况下保持音频播放

javascript - 在 TypeScript 中使用 JavaScript 类

javascript - 单击虚拟键盘图标时保持对输入框的关注