原生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打不开的时候, 我们就可以展示默认图片.

相关推荐
夏与冰17 小时前
Vue2项目中数据字典的使用封装
前端·javascript·vue.js·elementui
map_vis_3d18 小时前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
kyriewen18 小时前
我把 7 个 UI 库的下拉框用键盘敲了一遍,3 家出了岔子
前端·javascript·程序员
陈随易18 小时前
MoonBit 2026 深圳线下交流分享
前端·后端·程序员
玖米GEO运营王总监18 小时前
抖音和视频号算法区别:玖米快跑的双端分发信号与内容适配对比
java·前端·人工智能
鼓掌MVP18 小时前
华为云码道实战:用 CodeArts Agent + 智能化搜索工具 API 调用自主开发「非遗文旅宣传卡生成器」
前端·人工智能·ai·html·ai编程·ai智能体·ai自动化
不要试图纠正别人19 小时前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
tryCbest19 小时前
Vue系列——第 24 篇:VueUse——组合式工具集的百宝箱
前端·vue.js
GuWenyue19 小时前
setInterval 里的 state 永远是 0?我把 React 闭包陷阱的 5 个反例全写了一遍
前端·react.js
Xeni19 小时前
从「会写」到「真懂」:SSE 流式输出的 20 行代码与 7 个坑
前端