仅在提示答案正确后才显示H1

时间:2018-09-01 10:57:22

标签: javascript html css

仅当用户在提示中输入正确的输入(30)后,我才需要显示“生日快乐”。我希望默认情况下将其隐藏。 我这样做的原因是我想稍后在此h1标签中添加一些CSS动画。

function myFunction() {
    var txt;
    var myTextbox = document.getElementById("bday");
    var Age = prompt("How old are you?:");
    if (Age == 30) {
      return myTextbox;
    } else {
      txt = "Really? ";
    }
    document.getElementById("demo").innerHTML = txt;
  }
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday"> Happy Birthday! </h2>

2 个答案:

答案 0 :(得分:1)

您需要向id =“ bday”的元素添加隐藏属性

document.getElementById("bday").style.display = "none";

function myFunction() {
    var txt;
    var myTextbox = document.getElementById("bday");
    var Age = prompt("How old are you?:");
    if (Age == 30) {
      document.getElementById("bday").style.display = "block";
      return myTextbox;
    } else {
      txt = "Really? ";
    }
    document.getElementById("demo").innerHTML = txt;
 
  }
  
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday" hidden> Happy Birthday! </h2>

答案 1 :(得分:0)

无需复杂,您可以减少标记并改善功能:

function myFunction() {
  var myTextbox = document.getElementById("response");
  var Age = prompt("How old are you?");
  if (Age == 30) {
    myTextbox.innerHTML = "Happy Birthday!";
  } else if (Age == null) { // addition, if clicked on cancel
    myTextbox.innerHTML = "";
  } else {
    myTextbox.innerHTML = "Really?";
  }
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="response"></h1>