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

相关推荐
SEO_juper11 分钟前
Node.js Product 结构化数据生成器:给产品页一键生成 JSON-LD
开发语言·前端·javascript·人工智能·node.js·json·1024程序员节
Mh8 小时前
基于踩过的坑,浅聊一下vh、svh、lvh、dvh
前端·css·设计模式
刘小灰8 小时前
返璞归真,我开始更新博客了
前端·后端
郝学胜-神的一滴9 小时前
Effective STL 条款15:注意字符串实现上的差异
java·开发语言·数据结构·c++·算法·visualstudio
sharemylove9 小时前
Java学习笔记 —— 面向对象专题
java·开发语言·笔记·学习·课程设计
圆心角9 小时前
Agent 上下文原理:为什么“记住”比“推理”更难
前端·面试·agent
代码民工正电荷10 小时前
JAVA学习基础(一)
java·开发语言·学习
杜子不疼.12 小时前
从 Apache HTTP Server 到 CivetWeb:在鸿蒙 PC 的 3.1 MiB HAP 里嵌入 Web 服务器
前端·apache·harmonyos
kyriewen13 小时前
AI 生成率进了 KPI,最慌的是写代码最快的人
前端·javascript·程序员
SoaringHeart13 小时前
Flutter组件封装:聊天气包图片组件NChatBubble
前端·flutter