如何使用JavaScript或jQuery实现图片加载失败时显示其title内容
实现思路
核心逻辑是监听图片加载失败的error事件,触发后将图片元素替换为展示title属性内容的占位容器,兼容性好且不会破坏原有页面布局。
jQuery实现方案
$('img').on("error", function() { const $img = $(this); const titleText = $img.attr('title') || '图片加载失败'; // title为空时的默认提示 // 生成占位容器 const $placeholder = $('<span></span>').text(titleText); // 继承原图片类名,适配原有样式规则 $placeholder.attr('class', $img.attr('class')); // 适配原图片尺寸,占位样式可按需自定义修改 $placeholder.css({ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: $img.width() ? `${$img.width()}px` : '120px', height: $img.height() ? `${$img.height()}px` : '120px', border: '1px solid #e5e7eb', backgroundColor: '#f3f4f6', color: '#6b7280', fontSize: '14px', padding: '4px' }); // 替换原图片元素 $img.replaceWith($placeholder); });
如果页面存在动态插入的图片,使用事件委托写法兼容:
$(document).on('error', 'img', function() { // 同上处理逻辑 });
原生JavaScript实现方案(无需jQuery)
document.querySelectorAll('img').forEach(img => { img.addEventListener('error', function() { const titleText = this.title || '图片加载失败'; const placeholder = document.createElement('span'); placeholder.textContent = titleText; placeholder.className = this.className; // 样式适配同上方jQuery版本,可按需修改 placeholder.style.cssText = ` display: inline-flex; align-items: center; justify-content: center; width: ${this.width ? this.width + 'px' : '120px'}; height: ${this.height ? this.height + 'px' : '120px'}; border: 1px solid #e5e7eb; background-color: #f3f4f6; color: #6b7280; font-size: 14px; padding: 4px; `; this.replaceWith(placeholder); }); });
可选优化点
- 可以将占位容器的样式提前写入CSS类,直接给占位元素加类名即可,不用内联写样式,维护更方便
- 如果需要保留原img的其他属性,可以在替换前将需要的属性复制到占位元素上
内容的提问来源于stack exchange,提问作者Jegan Baskaran
相关产品推荐
相关产品推荐

