原生js: 准生产环境图片404但是线上环境是正常的

问:

html 复制代码
<div class="helpWarp">
        <div class="user">
            <dl>
                <dt><img src="https://xxxx.xxxx.com/xxxx/xxxx/xxxx/xxxx.svg" alt=""></dt>
                <dd>
                    <p>Hi,网友张三</p>
                    <span>人工客服会全力帮助您解决问题</span>
                </dd>
            </dl>
        </div>

这是我的代码, 现在准生产环境进入后 图片是404, 但是线上环境正常, 当图片404的时候, img默认就没有空间占用, 宽度高度都是0, 这时候是没有任何图片的, 为了解决这个问题, 请问怎么办?

回答:

javascript 复制代码
// 修改准生产环境, 用户没有图片的话, 头像元素不显示的问题
      const img = document.querySelector('.helpWarp .user dl dt img');

        img.addEventListener('error', () => {
            console.log('Image failed to load');
            // Optionally, you can replace the broken image with a placeholder or another image
            img.src = '当img没有宽高的情况下, 放一张默认图片地址'; // Replace with your placeholder image path

            // Alternatively, you can add a placeholder div if you want to keep the image tag
            //img.style.display = 'none'; // Hide the broken image
            //const placeholder = document.createElement('div');
            //placeholder.className = 'error-placeholder';
            //placeholder.textContent = 'Image not available'; // Or any other placeholder text
            //img.parentNode.appendChild(placeholder);
        });

        // Optional: Handle cases where the image loads successfully
        img.addEventListener('load', () => {
            console.log('Image loaded successfully');
        });

这样当图片在某些环境404打不开的时候, 我们就可以展示默认图片.

相关推荐
universe_0116 小时前
day27|前端框架学习
前端·笔记
沙尘暴炒饭16 小时前
前端vue使用canvas封装图片标注功能,鼠标画矩形框,标注文字 包含下载标注之后的图片
前端·vue.js·计算机外设
平生不喜凡桃李16 小时前
C++ 异常
android·java·c++
SamDeepThinking16 小时前
用设计模式重构核心业务代码的一次实战
java·后端·设计模式
endcy201616 小时前
mybatis-plus多租户兼容多字段租户标识
java·mybatis-plus·多租户
百思可瑞教育16 小时前
Vue中使用keep-alive实现页面前进刷新、后退缓存的完整方案
前端·javascript·vue.js·缓存·uni-app·北京百思可瑞教育
yinuo16 小时前
Uni-App跨端实战:APP的WebView与H5通信全流程解析(03)
前端
yinuo16 小时前
Uni-App跨端实战:支付宝小程序WebView与H5通信全流程解析(02)
前端
李游Leo17 小时前
Redis 持久化与高可用实践(RDB / AOF / Sentinel / Cluster 全解析)
java·spring·bootstrap
木心操作17 小时前
js生成excel表格进阶版
开发语言·javascript·ecmascript