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

相关推荐
古夕几秒前
Promise A+ 规范解读
前端·javascript
古夕几秒前
Promise 基础概念与实践详解
前端·javascript
SameX1 分钟前
HarmonyOS Next 枚举递归定义与表达式树建模:从理论到实践
前端
SameX3 分钟前
HarmonyOS Next自定义枚举与标准库的协同:Option与Result
前端
用户5806139393004 分钟前
深度解析:解决大型 Git 仓库克隆失败的完整指南
前端
白瓷梅子汤4 分钟前
跟着官方示例学习 @tanStack-table --- Column Ordering
前端·react.js
异常君5 分钟前
MyBatis 中 SqlSessionFactory 和 SqlSession 的线程安全性深度分析
java·面试·mybatis
我想说一句5 分钟前
React组件化开发实战:从"待办事项"看前端乐高搭建术
前端·javascript·react.js
古夕6 分钟前
Promise 解决过程(Promise Resolution Procedure)详解
前端·javascript
spionbo6 分钟前
Vue 自定义进度条实现方法与应用场景解析
前端·面试