无法修改外部HTML时如何编写JavaScript函数将加载失败的图片替换为指定提示
实现思路
核心是利用图片加载失败触发的error事件做全局监听,不需要修改原HTML的img标签属性,同时兼容静态和动态插入的外部图片。
代码实现
// 全局监听图片加载错误(捕获阶段触发,适配不冒泡的error事件) document.addEventListener('error', function(e) { // 判断触发事件的元素是否是img标签 if (e.target.tagName.toLowerCase() === 'img') { // 替换img元素为提示文本容器 const tipEle = document.createElement('div'); tipEle.innerText = '请登录以查看该图片'; // 适配原图片尺寸,可根据需求自定义样式 tipEle.style.width = e.target.offsetWidth ? `${e.target.offsetWidth}px` : '200px'; tipEle.style.height = e.target.offsetHeight ? `${e.target.offsetHeight}px` : '120px'; tipEle.style.display = 'inline-flex'; tipEle.style.alignItems = 'center'; tipEle.style.justifyContent = 'center'; tipEle.style.border = '1px solid #eee'; tipEle.style.backgroundColor = '#f5f5f5'; tipEle.style.color = '#666'; // 替换原加载失败的图片 e.target.replaceWith(tipEle); } }, true); // 最后一个参数设为true,开启捕获阶段监听,否则无法捕获img的error事件
注意事项
- 捕获阶段的监听可以覆盖所有已经存在的静态img,以及后续动态插入到页面的img元素,不需要额外遍历绑定事件
- 可以根据业务需求调整提示容器的样式,比如适配原图片的尺寸、自定义文字大小颜色等
- 如果需要区分是加载失败还是其他原因导致的图片异常,可以额外加
e.target.src的校验逻辑
内容的提问来源于stack exchange,提问作者Simran Gehani
相关产品推荐
相关产品推荐

