当前位置 博文首页 > 文章内容

    JS实现简单计数器

    作者:shunshunshun18 栏目:未分类 时间:2021-10-13 14:44:40

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    用HTML CSS和JavaScript实现简单计数器,有加、减和零三个按钮,分别实现加一、减一和归零操作。下面先看一下效果图。

    HTML代码

    <div class="body">
       <div class="text">
        <font>Counter</font>
       </div>
       <div class="count" >
        <span id="demo" class="ft">
         2
        </span>
       </div>
       <div class="btn">
        <button type="button" οnclick="add()" class="btn1">+</button>
        <button type="button" οnclick="zero()" class="btn2">零</button>
        <button type="button" οnclick="sub()" class="btn1">-</button>
    
       </div>
    </div>

    CSS代码

     .body {
        width: 300px;
        height: 500px;
        background-color: #211d5a;
        border-radius: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
       }
       
       .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: 10px solid;
        border-color: rgb(79, 59, 156);
        border-radius: 50%;
        display: flex;
       }
       
       .ft {
        font-size: 100px;
        color: #fff;
        /*left: 50%;
                    margin-left: -102px;
                    margin-top: 40px;*/
        margin: auto;
       }
       
       .btn {
        width: 220px;
        display: flex;
        /*flex-direction: row;*/
        justify-content: space-between;
        margin-top: 60px;
       }
       
       .btn1 {
        width: 50px;
        height: 30px;
        border: 0px;
        border-radius: 4px;
        background-color: rgb(79, 59, 156);
        font-size: 20px;
        color: #efdaff;
       }
       
       .btn2 {
        width: 50px;
        height: 30px;
        border: 0px;
        border-radius: 4px;
        background-color: rgb(79, 59, 156);
        font-size: 22px;
        color: #efdaff;
       }

    tips:弹性盒子display:flex布局+margin:auto可实现完美居中。

    JS代码

    <script>
       var counter = document.getElementById("demo").innerHTML;
       function add() {
         counter++;
         document.getElementById("demo").innerHTML = counter;
       }
    
       function sub() {
        if(counter == 0) {
           counter = 0;
        } else {
         counter--;
            document.getElementById("demo").innerHTML = counter;
        }
       }
    
       function zero() {
        counter = 0;
           document.getElementById("demo").innerHTML = counter;
       }
    </script>

    以上代码即可实现效果。

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IIS7站长之家博文。