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

相关推荐
GISer_Jing6 分钟前
1.17-1.23日博客之星投票,每日可投
前端·人工智能·arcgis
好大哥呀7 分钟前
Java 中的 Spring 框架
java·开发语言·spring
计算机毕设指导67 分钟前
基于微信小程序技术校园拼车系统【源码文末联系】
java·spring boot·mysql·微信小程序·小程序·tomcat·maven
大道之简8 分钟前
SpringBoot自定义链路追踪
java·spring boot·spring
Charlie_lll8 分钟前
LibreOffice 实现 Word 转 PDF
java·spring boot·pdf·word
hhzz9 分钟前
Springboot项目中使用EasyPOI操作Excel(详细教程系列4/4)
java·spring boot·后端·spring·excel·poi·easypoi
代码游侠10 分钟前
学习笔记——ARM Cortex-A 裸机开发实战指南
linux·运维·开发语言·前端·arm开发·笔记
星火开发设计13 分钟前
表达式与语句:C++ 程序的执行逻辑基础
java·开发语言·c++·学习·知识·表达式
m0_7482546613 分钟前
CSS 编辑器
前端·css·编辑器
计算机毕设指导614 分钟前
基于微信小程序求职招聘-兼职管理系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·求职招聘