JavaScript简单的随机点名系统

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        #all {
            margin-top: 10px;
            width: 540px;
            height: 50px;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
        }

        .db {
            width: 100px;
            height: 50px;
            background-color: #fff;
            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
            border: 1px solid red;
            float: left;
            margin-left: 5px;
            line-height: 50px;
            text-align: center;
            /*color: red;*/
        }
    </style>
</head>
<body>
<input type="button" value="开始" id="start"/>

<div id="all">
    <div>小明</div>
    <div>小红</div>
    <div>小梁</div>
    <div>老王</div>
    <div>小绿</div>
</div>
<script src="common.js"></script>
<script>
    //为all中的div添加样式
    var divs = my$("all").getElementsByTagName("div");
    for (var i = 0; i < divs.length; i++) {
        divs[i].className = "db";
    }
    //点名
    my$("start").onclick = function () {
        if (this.value == "开始") {
            this.value = "停止";
            timeId = setInterval(function () {
                for (var i = 0; i < divs.length; i++) {
                    divs[i].style.backgroundColor = "";
                    divs[i].style.color = "";
                }
                divs[parseInt(Math.random() * divs.length)].style.backgroundColor = "red";
            }, 100)
        } else {
            //清除定时器
            clearInterval(timeId);
            this.value = "开始";
        }
    };
</script>
</body>
</html>

common.js代码

function my$(id) {
    return document.getElementById(id);
}
原文地址:https://www.cnblogs.com/cuilichao/p/9384818.html