原生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 分钟前
从代码到像素:浏览器渲染原理与 React Fiber 架构的深度协作
前端·react.js·浏览器
Knight_AL21 分钟前
Spring Cloud Alibaba 项目中DataSource 配置失败?原来是 application.yml 和 bootstrap.yml 的坑
前端·bootstrap·html
怒放吧德德1 小时前
RocketMQ从实战到源码:初识RocketMQ
java·后端·rocketmq
怎么就重名了1 小时前
Kivy的属性系统
java·前端·数据库
daidaidaiyu1 小时前
一文入门 Spring Security with 单点登录(jasig)
java·spring
哈哈老师啊1 小时前
Springboot就业管理系统bk5uv(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·spring boot·spring
chao1898441 小时前
基于C#实现Modbus通信及CRC校验
java·开发语言·c#
hunjinYang1 小时前
源码配置——基于Gradle搭建spring-framework-6.2.15版本阅读环境
java·后端·spring
编程饭碗1 小时前
【Spring全局异常处理 早抛晚捕】
java·数据库·spring
咸鱼2.01 小时前
【java入门到放弃】Elasticsearch概念
java·elasticsearch·jenkins