Javascript猜数字游戏
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <div style="width:200px;height:200px;border:dashed;background-color:darkseagreen;border-width:1px;"> <p>1.猜測一个0到100的数<br />2.雙擊文本框重新輸入<br />3.輸入result顯示目標數值</p> <label id="lblResult" style="width:30px;background-color:crimson">显示对错</label> <br /> <label id="lblCount" style="background-color:darkcyan">猜测次数:0</label> <br /> <input type="text" id="txtNum" onchange="getResult()" ondblclick="CaiShu()" /> <br /> <label id="lblDebug">Coded By Phoenix©2016</label> <button hidden="hidden" id="btnReset" onclick="reset()">重新開始</button> </div> <script> var shuzhi = parseInt(Math.random() * 100);//得到要让人家猜测的数 var cishu = 0; //document.getElementById("realValue").innerHTML = shuzhi; var lblResult = document.getElementById("lblResult"); var lblDebug = document.getElementById("lblDebug"); var txtNum = document.getElementById("txtNum"); function CaiShu() { var num = txtNum.value;//猜测的数 //alert(num); if (shuzhi>num) { lblResult.innerHTML = "猜小了"; cishu = cishu + 1; txtNum.textContent = ""; } if(shuzhi<num) { lblResult.innerHTML = "猜大了"; cishu = cishu + 1; txtNum.textContent = ""; } if(shuzhi==num) { lblResult.innerHTML = "猜對了"; document.getElementById("btnReset").hidden = null; } //顯示猜測次數 document.getElementById("lblCount").innerHTML ="猜測次數"+ cishu; } function reset() { shuzhi = parseInt(Math.random() * 100); cishu = 0; document.getElementById("btnReset").hidden = "hidden"; document.getElementById("txtNum").value = ""; document.getElementById("lblResult").innerHTML = "顯示對錯"; document.getElementById("lblCount").innerHTML = 0; } function getResult() { var result = txtNum.value == "result"; //lblDebug = result; if (result) { txtNum.value = shuzhi; } } </script> </body> </html>