如何在图片请求返回404但带内容时强制显示alt文本?
解决方法
你遇到的问题本质是:浏览器判断图片“加载成功”的标准是能解码出有效图片内容,哪怕服务器返回404状态码,只要返回的内容是可识别的图片,就不会触发onerror,只会显示这张错误图。要强制显示alt文本,得先校验请求的HTTP状态码,再决定是否加载图片。
下面是两种可行的实现方式:
方式一:用Fetch API先查状态码
先通过Fetch请求图片资源,确认状态码是2xx(成功)再把地址赋值给img的src;如果是4xx/5xx错误,就不设置src,让浏览器直接显示alt文本。
代码示例:
<html lang="en"> <body> <img data-src="https://thumbs.dreamstime.com/b/qqqqq.jpg" alt="ERROR"><br> <img data-src="https://iili.io/qqqqq.jpg" alt="ERROR"><br> <script> document.querySelectorAll('img[data-src]').forEach(img => { fetch(img.dataset.src) .then(res => { if (res.ok) { img.src = img.dataset.src; } else { // 状态不对,不加载图片,显示alt img.style.display = 'inline-block'; } }) .catch(() => { // 网络出错也显示alt img.style.display = 'inline-block'; }); }); </script> </body> </html>
方式二:XMLHttpRequest+Image对象组合
用XMLHttpRequest获取图片的状态码和内容,状态正常就把Blob数据转成URL给img,否则直接显示alt:
<html lang="en"> <body> <img data-src="https://thumbs.dreamstime.com/b/qqqqq.jpg" alt="ERROR"><br> <img data-src="https://iili.io/qqqqq.jpg" alt="ERROR"><br> <script> function checkAndLoad(img) { const src = img.dataset.src; const xhr = new XMLHttpRequest(); xhr.open('GET', src); xhr.responseType = 'blob'; xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { const blobUrl = URL.createObjectURL(xhr.response); img.src = blobUrl; img.onload = () => URL.revokeObjectURL(blobUrl); } else { img.style.display = 'inline-block'; } }; xhr.onerror = () => { img.style.display = 'inline-block'; }; xhr.send(); } document.querySelectorAll('img[data-src]').forEach(checkAndLoad); </script> </body> </html>
注意点
- 为啥
onerror没用?因为服务器返回的404错误图是有效的图片文件,浏览器能正常解码,所以判定加载成功,不会触发错误事件。 - 样式设置:默认没src的img可能显示空白占位框,加
display: inline-block能让alt文本正常显示出来,也可以根据需求调整字体、大小等样式。
内容的提问来源于stack exchange,提问作者Alex O
相关产品推荐
相关产品推荐

