首页 > 解决方案 > 如何让我的代码每个问题只显示一张图片

问题描述

const question = document.querySelector('#question');
const choices = Array.from(document.querySelectorAll('.choice-text'));
const progressText = document.querySelector('#progressText');
const scoreText = document.querySelector('#score');

let currentQuestion = {}
let acceptingAnswers = true
let score = 0
let questionCounter = 0
let availableQuestions = []


let questions = [
    {
        question: "Question 1",
        choice1: "Spain",
        choice2: "France",
        choice3: "Colombia",
        choice4: "China",
        answer: 2,
    },
    {
        question:"Question 2",
        choice1: "Hungary",
        choice2: "Switzerland",
        choice3: "Chile",
        choice4: "Austrailia",
        answer: 1,
    },
    {
        question: "Question 3",
        choice1: "Chile",
        choice2: "Brazil",
        choice3: "New Zealand",
        choice4: "Morocco",
        answer: 4,
    },
]
const SCORE_POINTS = 1
const MAX_QUESTIONS = 6

function startGame(){
    questionCounter = 0
    score = 0
    availableQuestions = [...questions]
    getNewQuestion()
}

function getNewQuestion(){
    if(availableQuestions.length === 0 || questionCounter > MAX_QUESTIONS) {
        localStorage.setItem('mostRecentScore', score)
        return window.location.assign('end.html')
    }
    questionCounter++
    progressText.innerText = `Question ${questionCounter} of ${MAX_QUESTIONS}`
    // progressBarFull.style.width = `${(questionCounter/MAX_QUESTIONS) * 100}%`
    
    const questionsIndex = Math.floor(Math.random() * availableQuestions.length)
    currentQuestion = availableQuestions[questionsIndex]
    question.innerText = currentQuestion.question

    choices.forEach(choice => {
        const number = choice.dataset['number']
        choice.innerText = currentQuestion['choice' + number]
    })

    availableQuestions.splice(questionsIndex, 1)

    acceptingAnswers = true
}

choices.forEach(choice => {
    choice.addEventListener('click', e => {
        if(!acceptingAnswers) return

        acceptingAnswers = false
        const selectedChoice = e.target
        const selectedAnswer = selectedChoice.dataset['number']

        let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'

        if(classToApply === 'correct') {
            incrementScore(SCORE_POINTS)
        }

        selectedChoice.parentElement.classList.add(classToApply)

        setTimeout(() => {
            selectedChoice.parentElement.classList.remove(classToApply)
            getNewQuestion()

        }, 1000)
    })
})

function incrementScore(num){
    score +=num
    scoreText.innerText = score
}

startGame()
body{
    background-color: gray;
}
*{
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    font-size: 62.5%;
}
h1{
    text-align: center;
    font-size: 5.4rem;
    color: black;
    margin-bottom: 5rem;
}
h2{
    font-size: 4.2rem;
    margin-bottom: 4rem;
}
.container{
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 80rem;
    margin: 0 auto;
    padding: 2rem;
}
.flex-column{
    display: flex;
    flex-direction: column;
}
.flex-center{
    justify-content: center;
    align-items: center;
}
.justify-center{
    justify-content: center;
}
.text-center{
    text-align: center;
}
.hidden{
    display: none;
}
.btn{
    font-size: 2.4rem;
    padding:2rem 0;
    width: 30rem;
    text-align: center;
    margin-bottom: 1rem;
    text-decoration: none;
    color: rgb(29, 26, 26);
    background: lightblue;
    border-radius: 4px;
}
.btn:hover{
    cursor: pointer;
    background: teal;
    box-shadow: rgb(130, 170, 183);
    transition:transform 150ms;
    transform: scale(1.03);
}
.btn[disabled]:hover{
    cursor: not-allowed;
    box-shadow: none;
    transform: none;
}
body {
    color: black;
}
.choice-container {
    display: flex;
    margin-bottom: 0.8rem;
    width: 100%;
    border-radius: 4px;
    background: lightblue;
    font-size: 3rem;
    min-width: 80rem;
}

.choice-container:hover {
    cursor: pointer;
    box-shadow: 0 0.4rem 1.4rem 0 rgba(6, 103, 247, 0.5);
    transform: scale(1.02);
    transform: transform 100ms;
}

.choice-prefix {
    padding: 2rem 2.5rem;
    color: black
}

.choice-text {
    padding: 2rem;
    width: 100%;
}
.progressText{
    text-align: center;
}
.correct {
    background: green;
}

.incorrect {
    background: red;
}

/* Heads up Display */
#hud {
    display: flex;
    justify-content: space-between;
}

.hud-prefix {
    text-align: center;
    font-size: 2rem;
}

.hud-main-text {
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quiz Page</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="game.css">
    <style>
        img{
            align-self:  center;
            width: 80px;
            height: 150;
            padding-bottom: 50px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="game" class="justify-center flex-column">
            <div id="hud">
                <div class="hud-item">
                    <p id="progressText" class="hud-prefix">
                        Question
                    </p>
                    <div id="progressBarFull"></div>
                </div>
                <div class="hud-item">
                    <p class="hud-prefix">
                        Score
                    </p>
                    <h1 class="hud-main-text" id="score">
                        0
                    </h1>
                </div>
            </div>
            <h1 id="question">What is the answer to this question</h1>
            <img id="france" src="france.jpg">
            <img id="hungary" src="hungary.jpg">
            <img id="morocco" src="morocco.jpg">
            <div class="choice-container">
                <p class="choice-prefix">A</p>
                <p class="choice-text" data-number="1">Choice</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">B</p>
                <p class="choice-text" data-number="2">Choice 2</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">C</p>
                <p class="choice-text" data-number="3">Choice 3</p>
            </div>
            <div class="choice-container">
                <p class="choice-prefix">D</p>
                <p class="choice-text" data-number="4">Choice 4</p>
            </div>
        </div>
    </div>
    <script src="Flag.js"></script>
</body>
</html>

我正在创建一个问答游戏,向用户显示国旗,用户必须从四个选项中进行选择才能选择正确的一个。目前我已经显示了所有问题标志,因为我无法弄清楚每个问题如何只显示一张图片。有没有办法隐藏其他图片或将图像指定为问题的图像。测验还会在您每次玩时随机化,因此如果您第一次玩的第二次不同。

我添加了一个仅包含标志问题的代码片段。我的整个代码作为主页和显示最终分数并让用户再次播放的结束页面。

标签: javascripthtml

解决方案


给你:https ://codepen.io/chrisbradshaw/pen/yLaLLVo 。

  1. 从 HTML 中删除标志图像并添加:
<img src="" alt="quiz show question" id="flagImage" />
  1. 在问题对象中包含标志图像:
    {
        question: "Question 1",
        choice1: "Spain",
        choice2: "France",
        choice3: "Colombia",
        choice4: "China",
        answer: 2,
        flagImage: 'https://placekitten.com/200/300'
    }
  1. #flagImage为DOM img创建一个变量:
const flagImageHtml = document.querySelector('#flagImage');
  1. #flagImage更改当前问题时更新 DOM img 的 src :
flagImageHtml.src = currentQuestion.flagImage;

推荐阅读