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

相关推荐
搞不懂语言的程序员1 小时前
Spring源码解析 - SpringApplication run流程-refreshContext(context)源码分析
java·spring
_hermit:1 小时前
【从零开始java学习|第三篇】变量与数据类型的关联
java·学习
sql2008help5 小时前
使用spring-boot-starter-validation实现入参校验
java·开发语言
Mr_Air_Boy5 小时前
springboot集成xxl-job
java·spring boot·spring
Babybreath-5 小时前
Tomcat
java·tomcat
摇滚侠6 小时前
面试实战 问题二十三 如何判断索引是否生效,什么样的sql会导致索引失效
java
悟纤6 小时前
当生产环境卡成 PPT:Spring Boot 线程 Dump 捉妖指南 - 第544篇
java·spring boot·后端
学Java的bb6 小时前
JavaWeb-后端Web实战(IOC + DI)
前端
pe7er7 小时前
React Native 多环境配置全攻略:环境变量、iOS Scheme 和 Android Build Variant
前端·react native·react.js
柯北(jvxiao)7 小时前
Vue vs React 多维度剖析: 哪一个更适合大型项目?
前端·vue·react