在用JS选择提示后出现图片

问题描述 投票:1回答:1

用户输入适当的选项后,我需要使用条件语句将输入内容与我的选择进行比较,然后在网页上呈现图像。我知道我必须以某种方式使用CSS显示,以及可能的if / then语句,但是我不确定如何或在哪里使用。到目前为止,我的JavaScript中已经包含了这个。我不确定应该使用什么,以便在用户输入“红色”时出现图片(与霍格沃茨有关)。任何正确方向的提示?

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;
}
javascript html css if-statement prompt
1个回答
0
投票

您可以在页面上添加<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;
}

比制作4个由display:block显示的隐藏图像更好,因为浏览器甚至下载隐藏图像。

© www.soinside.com 2019 - 2024. All rights reserved.