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

相关推荐
郭优秀的笔记2 分钟前
html鼠标悬浮提示功能
android·javascript·html
慧一居士3 分钟前
npm install 各参数使用说明, 和使用场景说明
前端
无籽西瓜a6 分钟前
ArrayList和LinkedList的区别
java
冰暮流星10 分钟前
if与switch的区分
javascript
Elieal10 分钟前
@Api 系列注解
java·开发语言
Remember_99311 分钟前
【数据结构】深入理解Map和Set:从搜索树到哈希表的完整解析
java·开发语言·数据结构·算法·leetcode·哈希算法·散列表
小楼v12 分钟前
消息队列的核心概念与应用(RabbitMQ快速入门)
java·后端·消息队列·rabbitmq·死信队列·交换机·安装步骤
小北方城市网17 分钟前
接口性能优化实战:从秒级到毫秒级
java·spring boot·redis·后端·python·性能优化
小北方城市网19 分钟前
Redis 缓存设计与避坑实战:解决穿透 / 击穿 / 雪崩
java·大数据·数据库·redis·python·elasticsearch·缓存