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

相关推荐
我真的是大笨蛋3 分钟前
MVCC解析
java·数据库·spring boot·sql·mysql·设计模式·设计规范
秃头续命码农人5 分钟前
谈谈对Spring、Spring MVC、SpringBoot、SpringCloud,Mybatis框架的理解
java·spring boot·spring·mvc·maven·mybatis
比特森林探险记7 分钟前
React基础:语法、组件与JSX
前端·javascript·react.js
ahauedu7 分钟前
SpringBoot 3.5.10引入springdoc-openapi-starter-webmvc-ui版本
java·spring boot·后端
我是咸鱼不闲呀8 分钟前
力扣Hot100系列15(Java)——[二叉树]总结(有效的括号,最小栈,字符串解码,每日温度,柱状图中最大的矩形)
java·算法·leetcode
沉默-_-15 分钟前
MyBatis 学习笔记
java·开发语言·tomcat
未来龙皇小蓝16 分钟前
Spring内置常见线程池配置及相关概念
java·后端·spring·系统架构
Elias不吃糖17 分钟前
Java 常用数据结构:API + 实现类型 + 核心原理 + 例子 + 选型与性能(完整版)
java·数据结构·性能·实现类
会游泳的石头18 分钟前
构建企业级知识库智能问答系统:基于 Java 与 Spring Boot 的轻量实现
java·开发语言·spring boot·ai
宁雨桥27 分钟前
Vue项目中iframe嵌入页面实现免登录的完整指南
前端·javascript·vue.js