看你需要猜几次才能猜到那个正确的数字!
效果图:

代码如下:
004 | < meta http-equiv = "content-type" content = "text/html; charset=utf-8" /> |
006 | < script type = "text/javascript" charset = "utf-8" > |
007 | window.onload = newgame; //页面载入的时候就开始一个新的游戏 |
008 | window.onpopstate = popState; //处理历史记录相关事件 |
009 | var state, ui; //全局变量,在newgame()方法中会对其初始化 |
010 | function newgame(playagain) { |
012 | heading: null, //文档最上面的< h1 >元素 |
013 | prompt: null, //要求用户输入一个猜测数字 |
014 | input: null, //用户输入猜测数字的地方 |
015 | low: null, //可视化的三个表格单元格 |
020 | for(var id in ui) ui[id] = document.getElementById(id); |
021 | //给input字段定义一个事件处理程序函数 |
022 | ui.input.onchange = handleGuess; |
025 | n: Math.floor(99 * Math.random())+1, //整数: 0 < n <100 |
027 | high: 100, //可猜数字范围上限 |
029 | guess: undefined //最后一次猜测 |
033 | if (playagain === true)save(state); |
035 | function save(state) { |
036 | if (!history.pushState) return; //如果pushState()方法没有定义,则什么也不做 |
039 | var url = "#guess" + state.guessnum; |
041 | history.pushState(state, //要保存的状态对象 |
043 | url); //状态URL:对书签是没有用的 |
045 | //这是onpopstate的事件处理程序,用于恢复历史状态 |
046 | function popState(event) { |
049 | state = event .state; //恢复历史状态 |
050 | display(state); //显示恢复的状态 |
052 | history.replaceState(state, "", "#guess" + state.guessnum); |
055 | //每次猜测一个数字的时候,都会调用此事件处理程序 |
056 | //此处理程序用于更新游戏的状态、保存游戏状态并显示游戏状态 |
057 | function handleGuess() { |
059 | var g = parseInt (this.value); |
061 | if ((g > state.low) && (g < state.high )) { |
063 | if (g < state.n) state.low = g ; |
064 | else if (g > state.n) state.high = g; |
073 | alert("请输入大于" + state.low + "和小于" + state.high); |
077 | function display(state) { |
079 | ui.heading.innerHTML = document.title ="我在想一个" + state.low + "到" + state.high + "之间的数字!"; |
082 | ui.low.style.width = state.low + "%"; |
083 | ui.mid.style.width = (state.high-state.low) + "%"; |
084 | ui.high.style.width = (100-state.high) + "%"; |
086 | //确保input字段是可见的、空的并且是聚焦的 |
087 | ui.input.style.visibility = "visible"; |
092 | if (state.guess === undefined) |
093 | ui.prompt.innerHTML = "输入你的猜测:"; |
094 | else if (state.guess < state.n ) |
095 | ui.prompt.innerHTML = state .guess + "低了,再猜一次:"; |
096 | else if (state.guess > state.n) |
097 | ui.prompt.innerHTML = state.guess + "高了,再猜一次:"; |
099 | //当猜对了的时候,就隐藏input字段并显示“再玩一次”按钮 |
100 | ui.input.style.visibility = "hidden"; |
101 | ui.heading.innerHTML = document.title = state.guess + "正确!"; |
102 | ui.prompt.innerHTML = "你赢了 < button onclick = 'newgame(true)' >再玩一次</ button >"; |
107 | #prompt { font-size: 16pt;} |
108 | table { width: 90%; margin:10px; margin-left:5%;} |
109 | #low, #high { background-color:lightgray; height:1em; } |
110 | #mid { background-color:green;} |
114 | < h1 id = "heading" >我在想一个数字...</ h1 > |
122 | < label id = "prompt" ></ label > |
123 | < input id = "input" type = "text" > |
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!