You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS使用img.src加载图片失效,VSCode提示.src相关错误如何解决?

问题描述

按照教程指导尝试在JS中通过img.src加载图片,代码无法运行,核对后确认写法和教程完全一致。VSCode仅将.src部分标记为错误,且无论当前时间是几点,所有图片都无法加载,查找类似问题未找到解决方案。

相关代码

JS代码(ex002.js)

function carregar(){
    var msg = window.document.getElementById('msg')
    var img = window.document.getElementById('foto')
    var data = new Date()
    var hora = data.getHours()
    msg.innerHTML = `Agora são ${hora} horas.`
    if(hora >= 0 && hora < 12) {
        //BOM DIA!!!!
        img.src= 'morning.png'
    } else if(hora >= 12 && hora < 18){
        //BOA TARDE!!!
        img.src = 'noon.png'
    }else{
        //BOA NOITE!!!
        img.src = 'night.png'
    }
}

HTML代码

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hora do dia</title>
    <link rel="stylesheet" href="ex002.css">
</head>
<body onload="carregar()">
    <header>
        <h1>Hora do Dia</h1>
    </header>
        <section>  
            <div id="msg">
                Aqui vai aparecer a mensagem
            </div>
            <div id="foto">
                <img src="" alt="foto equivalente ao horário atual">
            </div>
        </section>
    <footer>
        <p>&COPY; CursoEmVídeo </p>
    </footer>
    <script src="ex002.js"></script>
</body>
</html>
根因与修复方案

故障属于典型的新手常见基础错误:id="foto"被设置在了div标签上,而非img标签上。div元素本身不存在src属性,所以JS中给img.src赋值时会抛出错误,图片自然无法加载。

修复代码示例

仅需要将id="foto"从外层div移动到img标签上即可:

<div>
    <img id="foto" src="" alt="foto equivalente ao horário atual">
</div>

内容的提问来源于stack exchange,提问作者Tarffie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 12:45:02