Web - JS当中的数组、循环、随机数和定时器的使用训练(随机点名器)

随机点名器训练,配套的还有网页轮播图训练
在这里插入图片描述
做出来的效果:
在这里插入图片描述
在这里插入图片描述
代码如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机点名</title>
    <style>
        /* 页面css样式设置 */
        .parent{
            height: 400px;
            width: 800px;
            background-color: #f5541b;
            border-radius: 10px;/* 设置元素的圆角 */
            margin: 10px auto;/*上下边框设置10px,左右设置为auto是为适应浏览器尺寸变化时可随着变换*/
            position: relative;/*把psition设置为relative,使得它的子块以它为标准进行边框设置*/
        }
        .box{
            width: 600px;
            height: 100px;
            border-radius: 10px;
            background-color: #bdb9a6;
            position: absolute;/*以父块为基础作边框设置*/
            margin-top: 100px;
            margin-left: 100px;/* (800-300)/2=250 */
            font-weight: bold;/*字体加粗*/
            font-size: 70px;
            text-align: center;/*文本居中*/
        }
        .button{
            width: 100px;
            border-radius: 5px;
            background-color: green;
            position: absolute;/*以父块为基础作边框设置*/
            margin-top: 250px;
            margin-left: 350px;
            cursor: pointer;/*设置鼠标样式*/
        }
    </style>
</head>
<body>
    <h1 align="center">随机点名训练</h1>
    <div class="parent">
        <div class="box">随机点名器</div>
        <button class="button" onclick="fun()">开始</button>
    </div>
</body>
<script type="text/javascript">
    //数据准备,使用String的数据格式获取名字数组
    var nameList = new String("张三,李四,王二,麻子,小明,建国,益达,狗蛋");
    var nameArr = nameList.split(',');
    var mytime = null;

    function fun(){
        //获取对应的元素,window可有可无,若不写,系统window默认存在
        var button = window.document.getElementsByClassName('button')[0];

        if(mytime == null){//没有开始执行随机点名程序
            button.style.backgroundColor = "red";
            button.innerHTML = '停止';
            show();//调用show()方法
        }else{//说明直在执行show()
            button.style.backgroundColor = 'green';
            button.innerHTML = '开始';
            //重置mytime
            clearTimeout(mytime);
            mytime = null;
        }
    }
    //show()方法,不断切换class==box的元素的名字
    function show(){
        //获取class==box的对象
        var box = window.document.getElementsByClassName('box')[0];
        //获取随机整数,范围在0-nameLis.length之间
        var num = parseInt((Math.random()*10000) % nameArr.length);
        //设置box对应元素的值
        box.innerHTML = nameArr[num];
        //递归调用show()实现不断切换名字
        mytime = setTimeout("show()",10);
    }
</script>
</html>

刚刚学习,掌握得不扎实,许多属性都是靠查手册才知道用法。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值