朋友曾跟我提过随机点名的需求,想要跑马灯效果,顺手写了一下.纯原生js写法
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
#tabs td{
width: 100px;
height: 30px;
text-align: center;
}
</style>
</head>
<body>
<button id="btn">Go!</button>
<script>
//定义名字数组
var arrName =['小明','小花','小青',
'小兰','小绿','小芳','小紫','小里','小张',
'小王','小黑','小白','小玲','小贾','小郑','小狗'
,'小三','小四','小酒','小样','小杨','小木','晓晓'];
//表格常量
var tabW =5;
var tabH =5;
//搭建随机函数
var MathRond =function(arr){
return Math.floor(Math.random()*arr.length);
}
//搭建表格函数
var MyTab =function(tabWidth,tabHeight){
var oTab =document.createElement("table");
oTab.setAttribute('border','1');
oTab.setAttribute('id','tabs');
for(var i =0;i<tabHeight;i++){
var aTr =document.createElement("tr");
oTab.appendChild(aTr);
for(var j =0;j<tabWidth;j++){
var aTd =document.createElement("td");
oTab.getElementsByTagName("tr")[i].appendChild(aTd);
}
}
document.body.appendChild(oTab);
}
MyTab(tabW,tabH);
//把名字放表格里
function tabPreson(arr){
var oTab =document.getElementById("tabs");
for(var i =0;i<arr.length;i++){
oTab.getElementsByTagName("td")[i].innerHTML=arr[i];
oTab.getElementsByTagName("td")[i].style.backgroundColor='';
oTab.getElementsByTagName("td")[i].style.color='red';
}
oTab.getElementsByTagName("td")[MathRond(arr)].style.backgroundColor=getColor();
// oTab.getElementsByTagName("td")[MathRond(arr)].style.color='#fff';
}
//启动前先调用 ===
//跑马灯效果 =====修改版,随时停止跑马灯效果。
var paoma =true;
var timeId =null;
function paoMa(){
if(paoma){
timeId =setInterval(function(){
tabPreson(arrName);
},20);
paoma=false;
}else{
clearInterval(timeId);
paoma=true;
}
}
//随机颜色抽取
var getColor =function(){
var nums ='0123456789abcdef';
var str='#';
for(var i =0;i<6;i++){
str+=nums[MathRond(nums)]
}
return str;
}
var oBtn =document.getElementById("btn");
//点击开始点名
oBtn.onclick=function(){
paoMa();
}
</script>
</body>
</html>