html 代码
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
body {
position: relative;
text-align: center;
}
#students {
width: 672px;
margin: 0 auto;
}
#students div {
width: 100px;
height: 100px;
display: inline-block;
border: 1px dashed black;
font-size: 30px;
line-height: 100px;
text-align: center;
margin: 5px;
background-color: pink;
color: white;
}
#switch {
width: 100px;
height: 100px;
background-color: black;
color: white;
font-size: 30px;
line-height: 100px;
text-align: center;
position: absolute;
top: 50px;
left: 50px;
}
</style>
</head>
<body>
<div id="students"></div>
<div id="switch">开始</div>
</body>
<script type="text/javascript">
var oStudents = document.getElementById("students");
var nameArr = ["张三","李四","王二","李桥","独立","医院","哈哈","嘻嘻","佳佳","贝贝","宝宝","秀秀","丽丽","爱心","健康","麻古","散散","频频","想想","等等","小柒"];
var oBtn = document.getElementById("switch");
var str = "";
var timer = null;
var isSelect = false;
var lastNum = 0; //记录上一次变颜色的div的下标
var oDivs = oStudents.getElementsByTagName("div");
for(var i = 0; i < nameArr.length; i++) {
str += "<div>" + nameArr[i] + "</div>";
}
oStudents.innerHTML = str;
oBtn.onclick = function() {
isSelect = !isSelect;
if(isSelect) {
oBtn.innerHTML = "结束";
clearInterval(timer);
timer = setInterval(function() {
getName();
}, 50);
} else {
clearInterval(timer);
oBtn.innerHTML = "开始";
}
}
function getName() {
var num = Math.floor(Math.random() * (nameArr.length – 1 – 0 + 1) + 0);
oDivs[num].style.backgroundColor = "yellow";
oDivs[num].style.color = "black";
oDivs[lastNum].style.backgroundColor = "pink";
oDivs[lastNum].style.color = "white";
lastNum = num;
}
</script>
</html>
评论前必须登录!
注册