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

相关推荐
Mh6 小时前
我是如何设计品牌站组件库的?
前端·css·设计模式
程序员大阳7 小时前
副队长Vue3教程(2)--Vite 搭建 Vue 项目,认识目录结构
前端·javascript·vue.js·vite·创建项目·目录结构·项目结构
濮水大叔7 小时前
Cabloy/Zova 与 Next.js 的 SSR 水合差异
前端·typescript·next.js
SoaringHeart7 小时前
Flutter最佳实践:用 flutter_html 渲染富文本
前端·flutter
Resean02237 小时前
Spring 源码分析(二)配置类的解析与扫描
java·后端·spring
小毛球.8 小时前
第 3 篇:IDEA 最新版下载与完整安装教程(Mac)
java·macos·intellij-idea·idea
Flynt9 小时前
Chrome给AI编程助手塞了203篇前端规范,我拆包实测:检索0.77秒是真快,扫描器有点挑食
前端·chrome·ai编程
北城笑笑9 小时前
Vue 110 ,若依SSE流式接口限次空500排查与解决
前端·javascript·vue.js·后端·vue
Misnearch9 小时前
ScheduledExecutorService
java·线程池
程序员韩星9 小时前
OpenAI 兼容接口返回 404,先查请求地址,再查模型名
前端·人工智能·http