上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>选字游戏</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
list-style: none;
}
html{
font-size:62.5% ;
}
.div1{
width: 400px;
height: 600px;
margin: 0 auto;
overflow: hidden;
box-shadow: 0 0 3px gray;
}
.top{
height: 1.875rem;
/* background-color: pink; */
margin-top: 50px;
font-size: 2rem;
}
.top #time{
float: left;
margin-left: 5px;
}
.top #score{
float: right;
margin-right: 5px;
}
#showWord{
text-align: center;
line-height: 20rem;
font-size: 15rem;
margin-top: 50px;
}
.rule{
font-size: 2rem;
text-align: center;
margin-top: 30px;
}
ul{
height: 5rem;
display: flex;
justify-content: space-around;
align-items: center;
margin-top: 100px;
}
li{
width: 5rem;
height: 5rem;
line-height: 5rem;
font-size: 5rem;
}
</style>
</head>
<body>
<div class="div1">
<p class="top">
<span id="time">剩余时间:5</span>
<span id="score">得分:0</span>
</p>
<p id="showWord">黑</p>
<p class="rule">根据上面字的颜色在下面选择正确的字</p>
<ul>
<li>黑</li>
<li>黄</li>
<li>红</li>
<li>绿</li>
<li>蓝</li>
</ul>
</div>
</body>
<script>
//获取标签
var pShowWord=document.getElementById("showWord");
var lis=document.getElementsByTagName("li");
var spanTime=document.getElementById("time");
var spanScore=document.getElementById("score");
//数据源
var colors=["black","gold","tomato","greenyellow","deepskyblue"];
var words=["黑","黄","红","绿","蓝"];
//得分
var score=0;
//时间
var time=5;
//计时器
var timer=null;
//改变showword和li
function setView(){
pShowWord.innerHTML=words[rand(0,5)];
var index=rand(0,5);
pShowWord.style.color=colors[index];
pShowWord.index=index;
//设置li
setLi();
}
setView();
function setLi(){
//打乱数组
var wordIndex=[0,1,2,3,4].sort(function(a,b){
return Math.random()-0.5;
})
var colorIndex=[0,1,2,3,4].sort(function(a,b){
return Math.random()-0.5;
})
for(var i=0;i<lis.length;i++){
//文字的下标
var wi=wordIndex[i];
lis[i].innerHTML=words[wi];
lis[i].index=wi;
//颜色的下标
var ci=colorIndex[i];
lis[i].style.color=colors[ci];
}
}
//为li添加点击事件
for(var i=0;i<lis.length;i++){
lis[i].onclick=function(){
if(this.index===pShowWord.index){
//点对了
// 增加得分
score++;
spanScore.innerHTML="得分"+score;
//如果得分为1,则开始计时
if(score===1){
timer=setInterval(function(){
time-=0.05;
spanTime.innerHTML="剩余时间"+time.toFixed(2);
if(time<=0){
time=0;
spanTime.innerHTML="剩余时间:0";
//停止计时 结束游戏
clearInterval(timer);
alert("游戏结束!");
alert("恭喜您的得分是"+score);//alert阻塞线程
//游戏重新开始
again();
}
}, 50)
}
// 继续游戏
setView();
}
}
}
function again(){
//游戏重新开始
score=0;
time=5;
spanScore.innerHTML="得分:"+score;
spanTime.innerHTML="剩余时间:"+time;
setView();
}
//随机数
function rand(min,max ){
return Math.floor(Math.random()*(max-min)+min);
}
</script>
</html>
运行结果