学完js'后配合html和css做的小练习,整体逻辑还是比较简单的。先绘制页面,再用js写入逻辑。
html代码:
<body>
<div id="content">
<div id="box">
<h2 id="title">随机点名器</h2>
<p id="name">????</p>
<button id="start">开始点名</button>
<button id="stop">停止</button>
</div>
</div>
</body>
css代码:
<style type="text/css">
*{
padding: 0;
margin: 0;
}
html,body{
width: 100%;
height: 100%;
}
#content{
width: 100%;
height: 100%;
background-image: url("../bp.png");
background-repeat: no-repeat ;
background-size: 100% 100%;
position: relative;
}
#box{
background: rgba(38, 33, 33, 0.3);
position: absolute;
width: 300px;
height: 400px;
left: 50%;
top: 55px;
margin-left: -150px;
border-radius:10px ;
}
#title{
color: white;
text-align: center;
}
#name{
color: orangered;
position: relative;
top: 25px;
font-size: 50px;
text-align:center;
}
#start{
background: orange;
display: inline-block;
width: 90px;
height: 40px;
text-align: center;
position: absolute;
margin-top: 50px;
line-height: 40px;
left: 25px;
border-radius: 10px;
}
#stop{
background: orange;
display: inline-block;
width: 90px;
height: 40px;
text-align: center;
position: absolute;
margin-top: 50px;
line-height: 40px;
right: 25px;
border-radius: 10px;
}
</style>
js代码:
- 步骤:
- 先创建一个数组,用来存放姓名,可以改成自己班级的童鞋的名字
- 定义变量接收id属性
- 定义一个时间变量,用来接收定时器
- 给开始游戏按钮绑定一个点击事件,写一个定时器方法setInterval,点击开始按钮后,名字随机出现,显示在指定位置。
- 通过 Math.random()*names.length;获取数组的索引
- innerHtml改值
- 给停止按钮绑定清空定时器的功能clearInterval,点击停止后,出现随机姓名。
<script type="text/javascript">
window.onload=function () {
var names=["熊大","熊二","光头强","翠花","小明","李华","观音","如来","喜羊羊","懒羊羊","沸羊羊"];
var name1= document.getElementById("name");
var start= document.getElementById("start");
var stop= document.getElementById("stop");
var time=null;
start.onclick=function () {
time = setInterval(function (){
var num = Math.random()*names.length;
num =Math.floor(num);
var name = names[num];
name1.innerHTML=name;
}, 100);
}
stop.onclick=function () {
time=clearInterval(time);
}
}
</script>
效果: