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

相关推荐
李伟_Li慢慢几秒前
18-mini版WebGLRenderList
前端·three.js
李伟_Li慢慢2 分钟前
15-mini版WebGLMaterials
前端·three.js
ji_shuke8 分钟前
Vue3 前端批量打印 PDF/图片踩坑记:跨域、合并打印、对话框闪退与按钮一直 loading
前端·pdf·状态模式·pdf打印
李伟_Li慢慢8 分钟前
06-mini版WebGLState
前端·three.js
李伟_Li慢慢13 分钟前
04-three.js的渲染流程概览
前端·three.js
李伟_Li慢慢14 分钟前
07-WebGLProperties
前端·three.js
爱勇宝14 分钟前
AI 都能写代码了,还要学计算机吗?
前端·后端·程序员
cfm_291416 分钟前
Spring监听器
java·spring boot·后端
石像鬼₧魂石18 分钟前
【Y2Ksoft】四季贵州水世界乐园管理系统 —— 玻璃拟态 · 单文件HTML · 开箱即用
前端·html
涛涛ing21 分钟前
尤雨溪宣布:Vue 3.6 发布、Vue 4.0 启动、Vite 8 已落地
前端