使用 JS 从提示中做出选择后出现图片

Picture appears after a choice from prompt has been made w/ JS

在用户输入合适的选择后,我需要使用条件语句将输入与我的选择进行比较,然后在网页上呈现图像。我知道我必须以某种方式使用 CSS 显示,可能还有 if/then 语句,但我不完全确定如何使用或在何处使用。到目前为止,我的 javascript 中有这个。 我不确定我应该使用什么,这样如果用户输入 'red' 就会出现一张图片(它将与霍格沃茨相关)。有正确方向的提示吗?

function myFunction() {
    var text;
  var favColor = prompt("What color appeals most to you out of red, green, blue, or yellow?", "Let the game begin");
  switch(favColor.toLowerCase()) {
    case "blue":
      text = "Sounds like you like to think";
      break;
    case "red":
      text = "Feeling bold?";
      break;
    case "green":
      text = "Really? Interesting choice";
      break;
      case "yellow":
        text = "How very clever of you!"
          break;
    default:
      text = "C'mon! Pick one!";
  }
  document.getElementById("demo").innerHTML = text;
}

您可以在您的页面上添加 <img id="my-image" /> 元素并根据用户回答更改图像 src 属性:

var text;
var src;
var favColor = prompt("What color appeals most to you out of red, green, blue, or yellow?", "Let the game begin");
switch(favColor.toLowerCase()) {
  case "blue":
    text = "Sounds like you like to think";
    src = 'blue_img.jpg';
    break;
  case "red":
    text = "Feeling bold?";
    src = 'red_img.jpg';
    break;
  case "green":
    text = "Really? Interesting choice";
    src = 'green_img.jpg';
    break;
    case "yellow":
    text = "How very clever of you!"
    src = 'yellow_img.jpg';
        break;
  default:
    text = "C'mon! Pick one!";
}
document.getElementById("demo").innerHTML = text;
if( src ){
  document.getElementById( 'my-image' ).src = src;
}

这比 display:block 显示 4 个隐藏图像要好,因为浏览器甚至会下载隐藏图像。