码迷,mamicode.com
首页 > Web开发 > 详细

原生js代码挑战之动态添加双色球

时间:2017-03-30 22:42:51      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:creat   return   splay   length   复数   lin   tee   span   lock   

var ballArr = []; //存放已有的红球,用来排除重复和排序
window.onload = function(){
var btn = document.createElement("button");
btn.innerHTML = "按键开始传球!";
btn.onclick = turnRunGo;
document.getElementsByTagName("body")[0].appendChild(btn);
}
//当有重复数字时循环直到长度达到6
function turnRunGo(){
for(let i = 0;;i++){
if(ballArr.length < 6){
generateRandom();
}else{
sortArr();
break; //for循环结束
}
}
}
// 生成随机数
function generateRandom(){
var random = Math.ceil(Math.random()*33);
for(let i = 0 ; i < ballArr.length; i++){
if(ballArr[i] == random){
return false; //有重复时不执行放入
}
}
ballArr.push(random);
}
//由小到大排序
function sortArr(){
for(let i = 0;i < ballArr.length;i++){
for(let n = 0;n < i + 1;n++){
if(ballArr[n] > ballArr[i]){
var sec = ballArr[n];
ballArr[n] = ballArr[i];
ballArr[i] = sec;
}
}
}
pushArr();
}
//将随机数排序后放入html中
function pushArr(){
var div = document.createElement("div");
for(let i = 0;i < ballArr.length;i++){
var ball = document.createElement("span");
ball.style.display = "inline-block";
ball.style.width ="30px";
ball.style.height = "30px";
ball.style.color = "white";
ball.style.textAlign = "center";
ball.style.borderRadius = "20px";
ball.style.background = "red";
ball.innerHTML = ballArr[i];
div.appendChild(ball);
}
//放入蓝球
var ball = document.createElement("span");
ball.style.display = "inline-block";
ball.style.width ="30px";
ball.style.height = "30px";
ball.style.color = "white";
ball.style.textAlign = "center";
ball.style.borderRadius = "20px";
ball.style.background = "blue";
ball.innerHTML = Math.ceil(Math.random()*16);
div.appendChild(ball);
document.getElementsByTagName("body")[0].appendChild(div);
}

原生js代码挑战之动态添加双色球

标签:creat   return   splay   length   复数   lin   tee   span   lock   

原文地址:http://www.cnblogs.com/blackchaos/p/6648868.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!