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

如何在JavaScript开发的问答测验题目后方添加图片?

第一步:修改HTML结构,新增问题图片占位容器

在game-question-container区块和game-options-container区块之间插入img标签,用于显示当前问题的配套图片:

<div class="game-question-container">
    <h1 id="display-question"></h1>
</div>
<!-- 新增图片区域 开始 -->
<div class="game-question-image-container" style="text-align: center; margin: 1rem 0;">
    <img id="question-image" style="max-width: 80%; height: auto; border-radius: 8px;" alt="题目配图">
</div>
<!-- 新增图片区域 结束 -->
<div class="game-options-container">

第二步:修改JS题目数组,给每个题目增加配图字段

给questions数组里的每道题新增questionImg属性,填入对应题目的图片地址,没有配图的题目可以留空字符串:

const questions = [
    {
        question: "一周有多少天?",
        optionA: "10天",
        optionB: "14天",
        optionC: "5天",
        optionD: "7天",
        correctOption: "optionD",
        questionImg: "你的本地图片路径或者线上图片地址" // 替换成对应题目的实际图片地址
    },
    // 剩余所有题目都按照上面的格式新增questionImg字段即可
    // ......
]

第三步:修改题目渲染逻辑,加载当前题目的配图

修改NextQuestion函数,新增图片加载逻辑:

function NextQuestion(index) {
    handleQuestions()
    const currentQuestion = shuffledQuestions[index]
    document.getElementById("question-number").innerHTML = questionNumber
    document.getElementById("player-score").innerHTML = playerScore
    document.getElementById("display-question").innerHTML = currentQuestion.question;
    document.getElementById("option-one-label").innerHTML = currentQuestion.optionA;
    document.getElementById("option-two-label").innerHTML = currentQuestion.optionB;
    document.getElementById("option-three-label").innerHTML = currentQuestion.optionC;
    document.getElementById("option-four-label").innerHTML = currentQuestion.optionD;
    // 新增图片渲染逻辑 开始
    const questionImgDom = document.getElementById("question-image")
    if (currentQuestion.questionImg) {
        questionImgDom.src = currentQuestion.questionImg
        questionImgDom.style.display = "inline-block"
    } else {
        questionImgDom.style.display = "none"
    }
    // 新增图片渲染逻辑 结束
}

改完以上三步即可实现每道题加载对应配图的需求,你可以根据自己的需要调整图片容器的样式参数,比如宽度、边距、圆角等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:06:04