我有以下代码:
<img src="test.jpg" width="20" height="20"> some content 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/