随机抽人小效果

用原生实现随机抽人的小效果

css、html

<style type="text/css">
    div{
        width: 300px;
        height: 300px;
        border: 2px solid saddlebrown;
        text-align: center;
        line-height: 300px;
        font-size: 60px;
    }
    input{
        width:100px;
        height: 35px;
    }
</style>
<body>
    <input type="button" id="btn" value="开始"/><br/><br/><br/>
    <div id="box"></div>
    <img src="image/1.jpg" alt="" id="m1"/>        
</body>

js

<script src="../public.js"></script>
<script type="text/javascript">
    //思路 :开关变量控制定时器的启动和停止
    //   flag == true  按钮--停止   启动定时器 -- 换图 换名    
    var arr = ["王子","老谭","酸菜","牛肉面","豆芽","蜜芽","谢飞机","王小蒙","刘能","谢广坤","赵四","刘大脑袋"];
    var flag  =  true;
    var btn = document.getElementById("btn");
    btn.onclick = function(){
        if(flag){//flag 为true 按钮改为暂停,开始定时器,在box里换名字,换图
            this.value = "暂停";
            timer = setInterval(function(){
                var index = rand(0,11);
                $id("box").innerHTML = arr[index];
                $id("m1").src = "image/" + (index + 1) + ".jpg";
            },300)
        }else{//flag 为false 移出定时器,把按钮的value改为开始
            this.value = "开始";
            clearInterval(timer);
        }
        flag = !flag;
    }
</script>

public.js

function $id(id){//给我一个id名,返回一个这个id的元素
    return document.getElementById(id);
}
//求随机数
function rand(min,max){
    return Math.round(Math.random()*(max - min) + min);
}

//随机的16进制颜色
function getColor(){
    var str = "0123456789ABCDEF";//十六进制字符串
    var color = "#";
    for(var i = 0; i <= 5; i++){//取6个数
        color += str.charAt(rand(0,15));
        //rand(0,15)随机0-15之间的数,作为charAt()的下标,取出下标对应的字符
    }
    return color;
}
function zero(val){
    return val < 10 ? "0" + val : val;
}
//时间差
function diff(start,end){//2000-2018  2018 - 2000
    //console.log(start.getTime());
    return Math.abs(start.getTime() - end.getTime())/1000;
}
View Code

 

posted @ 2019-11-22 10:45  野鹤亦闲云  阅读(216)  评论(0编辑  收藏  举报