js+html简单计时器

                                    咱们话不多说!整活

第一步:创建html表单

<div class="body">
    <div class="text">
        Counter
    </div>
    <div class="count" >
    <span id="demo" class="ft">0
    </span>
    </div>
    <div class="btn">
        <button type="button" onclick="add()" class="btn1"></button>
        <button type="button" onclick="zero()" class="btn2"></button>
        <button type="button" onclick="sub()" class="btn1"></button>
        <button type="button" onclick="stop()" class="btn2">||</button>
    </div>
</div>

第二步:加入css样式使其看起来比较美观

 <style>
        .body {
            width: 300px;
            height: 500px;
            background-image: linear-gradient(rgb(11, 142, 229),white);//颜色渐变
            border-radius: 20px;//圆角边框
            display: flex;弹性盒子
            flex-direction: column;
            align-items: center;
            margin: 0 auto;居中
        }
        .text {
            font-size: 24px;
            color: white;
            margin-top: 60px;
            text-shadow: 2px 2px 2px #fff;//阴影
        }
        .count {
            position: relative;
            width: 200px;
            height: 200px;
            margin-top: 60px;
            border-color: rgb(11, 142, 229);
            border-radius: 50%;
            display: flex;
        }
        .ft {
            font-size: 100px;
            color: #fff;
            margin: auto;
        }

        .btn {
            width: 220px;
            display: flex;
            justify-content: space-between;//弹性布局:均匀分布
            margin-top: 60px;
        }

        .btn1 {
            width: 50px;
            height: 30px;
            border: 0px;
            border-radius: 4px;
            background-color: rgb(11, 142, 229);
            font-size: 20px;
            color: #efdaff;
        }

        .btn2 {
            width: 50px;
            height: 30px;
            border: 0px;
            border-radius: 4px;
            background-color:rgb(11, 142, 229);
            font-size: 22px;
            color: #efdaff;
        }
 </style>

第三步:加入js,使其动起来

 var counter = document.getElementById("demo").innerHTML;//定义一个变量counter
    function add() {//点击函数,当点击+号时,开始计数
        counter++;//counter自加
        document.getElementById("demo").innerHTML = counter+'s';
       counter=setTimeout(add,1000)//每间隔1000毫秒执行一次add函数
    }
    function sub() {//点击减号,函数执行
        if(counter == 0) {//如果counter等于0;counter=0;
            counter = 0;
        } else {如果counter不等于0;counter数值-1
            counter--;
            document.getElementById("demo").innerHTML = counter+'s';
        }
    }
    function zero() {//点击零,记数归零
        counter = 0;
        document.getElementById("demo").innerHTML = counter;
    }
    function stop() {//点击||,停止计数
            clearInterval(counter)
    }
</script>

 大体效果就是这样的:

问题:1.连续点击+号会造成数据刷新过快,也就是倍速计数,但是通过点击-号会减低倍速

           2.点击||号可停止计数,点击加号可开始计数;

如果后期发现问题,可联系小白及时改正; 

posted @ 2021-12-24 15:18  一克嗽  阅读(514)  评论(0)    收藏  举报