用户输入适当的选项后,我需要使用条件语句将输入内容与我的选择进行比较,然后在网页上呈现图像。我知道我必须以某种方式使用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;
}
您可以在页面上添加<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显示的隐藏图像更好,因为浏览器甚至下载隐藏图像。