首页 > 解决方案 > 在测验 javascript 中显示图像

问题描述

我正在尝试创建一个测验来测试用户对真实和虚假电子邮件的认识。我想要做的是在顶部显示“真假”的问题,然后在下方显示一个图像,用户需要查看该图像以确定它是真的还是假的。有两个按钮,真实的和虚假的,无论他们是否选择正确的答案,我都想将原始图像与带注释的版本交换 - 显示用户如何发现它是假的还是真的。

但是我不确定一旦提交答案后如何显示带注释的版本。有人可以帮忙吗?

function Quiz(questions) {
  this.score = 0;
  this.questions = questions;
  this.questionIndex = 0;
}

Quiz.prototype.getQuestionIndex = function() {
  return this.questions[this.questionIndex];
}

Quiz.prototype.guess = function(answer) {
  if (this.getQuestionIndex().isCorrectAnswer(answer)) {
    this.score++;
  }

  this.questionIndex++;
}

Quiz.prototype.isEnded = function() {
  return this.questionIndex === this.questions.length;
}


function Question(text, choices, answer) {

  this.text = text;
  this.choices = choices;
  this.answer = answer;
}

Question.prototype.isCorrectAnswer = function(choice) {
  return this.answer === choice;
}


function populate() {
  if (quiz.isEnded()) {
    showScores();
  } else {
    // show question
    var element = document.getElementById("question");
    element.innerHTML = quiz.getQuestionIndex().text;

    // show options
    var choices = quiz.getQuestionIndex().choices;
    for (var i = 0; i < choices.length; i++) {
      var element = document.getElementById("choice" + i);
      element.innerHTML = choices[i];
      guess("btn" + i, choices[i]);
    }

    showProgress();
  }
};

function guess(id, guess) {
  var button = document.getElementById(id);
  button.onclick = function() {
    quiz.guess(guess);
    populate();
  }
};


function showProgress() {
  var currentQuestionNumber = quiz.questionIndex + 1;
  var element = document.getElementById("progress");
  element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};

function showScores() {
  var gameOverHTML = "<h1>Result</h1>";
  gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
  var element = document.getElementById("quiz");
  element.innerHTML = gameOverHTML;
};

// create questions here
var questions = [
  new Question("<img src= 'netflix_fake.jpg' />", ["Real", "Fake"], "Fake"),
  new Question("<img src= 'dropbox_real.jpg' />", ["Real", "Fake"], "Real"),
  new Question("<img src= 'gov_real.jpg' />", ["Real", "Fake"], "Real"),
  new Question("<img src= 'paypal_fake.jpg' />", ["Real", "Fake"], "Fake"),
  new Question("<img src= 'gmail.jpg' />", ["Real", "Fake"], "Fake")
];

//create quiz
var quiz = new Quiz(questions);

// display
populate();
body {
  background-color: #538a70;
}

.grid {
  width: 600px;
  height: 500px;
  margin: 0 auto;
  background-color: #fff;
  padding: 10px 50px 50px 50px;
  border: 2px solid #cbcbcb;
}

.grid h1 {
  font-family: "sans-serif";
  font-size: 60px;
  text-align: center;
  color: #000000;
  padding: 2px 0px;
}

#score {
  color: #000000;
  text-align: center;
  font-size: 30px;
}

.grid #question {
  font-family: "monospace";
  font-size: 30px;
  color: #000000;
}

.buttons {
  margin-top: 30px;
}

#btn0,
#btn1,
#btn2,
#btn3 {
  background-color: #a0a0a0;
  width: 250px;
  font-size: 20px;
  color: #fff;
  border: 1px solid #1D3C6A;
  margin: 10px 40px 10px 0px;
  padding: 10px 10px;
}

#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
  cursor: pointer;
  background-color: #00994d;
}

#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
  outline: 0;
}

#progress {
  color: #2b2b2b;
  font-size: 18px;
}
<div class="grid">
  <div id="quiz">
    <h1>Can you spot the fake email?</h1>
    <hr style="margin-bottom: 20px">

    <p id="question"></p>

    <div class="buttons">
      <button id="btn0"><span id="choice0"></span></button>
      <button id="btn1"><span id="choice1"></span></button>

    </div>

    <hr style="margin-top: 50px">
    <footer>
      <p id="progress">Question x of y</p>
    </footer>
  </div>
</div>

标签: javascripthtmlcss

解决方案


当用户单击按钮时,我触发了类并添加了第二个名称,第二次我写了交换,我写了你基本上完整的项目,请阅读整个评论,以了解逻辑

//Calling Elements from DOM
const button = document.querySelectorAll(".check");
const images = document.querySelectorAll(".image");
const answer = document.querySelector("h1");

//Declaring variable to randomly insert any object there to insert source in DOM Image sources
let PreparedPhotos;

//Our Images Sources and With them are its fake or not
//fake: true - yes its fake
//fake: false - no its real
const image = [
    [
        {
            src:
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1200px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg",
            fake: true
        },
        {
            src:
                "http://graphics8.nytimes.com/images/2012/04/13/world/europe/mona-lisa-like-new-images/mona-lisa-like-new-images-custom4-v3.jpg",
            fake: false
        }
    ],
    [
        {
            src:
                "https://cdn.shopify.com/s/files/1/0849/4704/files/Creacion_de_Adan__Miguel_Angel_f5adb235-bfa8-4caa-8ffb-c5328cbad953_grande.jpg?12799626327330268216",
            fake: false
        },
        {
            src:
                "https://cdn.shopify.com/s/files/1/0849/4704/files/First-image_Fb-size_grande.jpg?10773543754915177139",
            fake: true
        }
    ]
];

//Genrating Random Photo on HTML
function setRandomPhoto() {
  //Random Number which will be length of our array of Object
  //if you array includes 20 object it will generate random number
  // 0 - 19
    const randomNumber = Math.floor(Math.random() * image.length);

  //Decalaring our already set variable as Array Object
    PreparedPhoto = image[randomNumber];
  //Our first DOM Image is Variables first object source
    images[0].src = PreparedPhoto[0].src;
  //and next image is next object source
    images[1].src = PreparedPhoto[1].src;
}

//when windows successfully loads, up function runs
window.addEventListener("load", () => {
    setRandomPhoto();
});

//buttons click
//forEach is High Order method, basically this is for Loop but when you want to 
//trigger click use forEach - (e) is single button whic will be clicked 
button.forEach((e) => {
    e.addEventListener("click", () => {
    //decalring variable before using it
        let filtered;

    //finding from our DOM image source if in our long array exists
    //same string or not as Image.src
    //if it exists filtered variable get declared with that found obect
        for (let i = 0; i < image.length; i++) {
            for (let k = 0; k < 2; k++) {
                if (image[i][k].src === images[0].src) {
                    filtered = image[i][k];
                }
            }
        }
        
      //basic if else statement, if clicked button is Fake and image is true
    //it outputs You are correct
    //if clicked button is Real and Image is false it outputs Correct
    //Else its false
    
    //Our image checking comes from filtered variable
        if (e.innerText === "Fake" && filtered.fake === true) {
            
            answer.innerText = "You Are Correct";
            
            images.forEach((image) => {
                image.classList.toggle("hidden");
            });
        } else if (e.innerText === "Real" && filtered.fake === false) {
            answer.innerText = "You Are Correct";
            images.forEach((image) => {
                image.classList.toggle("hidden");
            });
            
        } else {
            answer.innerHTML = "You are Wrong";
  
            images.forEach((image) => {
                image.classList.toggle("hidden");
            });
        }
    });
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.container {
    width: 100%;
    min-height: 100vh;
    display: flex;
    justify-content: space-around;
    align-items: center;
    flex-direction: column;
}
.image-fluid {
    display: flex;
}
.image-fluid .image {
    width: 200px;
    margin: 0 10px;
    transition: 0.5s;
}
.image-fluid .image:nth-child(1).hidden {
    transform: translateX(110px);
}
.image-fluid .image:nth-child(2).hidden {
    transform: translateX(-110px);
}
<div class="container">
    <div class="image-fluid">
        <img src="" class="image hidden">
        <img src="" class="image hidden">
    </div>
    <div class="button-fluid">
        <button class="check">Fake</button>
        <button class="check">Real</button>
    </div>
</div>

<h1></h1>


推荐阅读