1. 程式人生 > >用js實現按鈕加減,減到0停止

用js實現按鈕加減,減到0停止

html程式碼如下:

<span class="btngroup">
                            <button    id="btn1" class="button"><strong>+</strong></button>
                        <button id="btn2"  class="button"><strong>0</strong></button>
                            <button id="btn3" class="button" >-</button>
                        </span>


css程式碼如下:

.button {
    background-color: white;
    border: 4px solid #ACB4BE;
    color: #536277;
    display: inline-block;
    float: right;
    font-size: 30px;
    padding: 8px 21px;
    text-align: center;
    text-decoration: none;
    &:nth-child(3) {
        border-bottom-left-radius: 10px;
        border-top-left-radius: 10px;
        border-right: 0;
        color: #A9B1BB;
    }
    &:nth-child(1) {
        border-bottom-right-radius: 10px;
        border-top-right-radius: 10px;
        border-left: 0;
    }
}

js程式碼如下:

window.onload=function(){
    		var count=1;
             var count1=1;
    		var adult=document.getElementById("btn1");
            var adcount=document.getElementById("btn2");
            var adco=document.getElementById("btn3");

            var child=document.getElementById("btn4");
    		var chcount=document.getElementById("btn5");
            var chco=document.getElementById("btn6");

                adult.onclick=function(){
                   
                count++;
                adcount.innerHTML=count;
                  adco.onclick=function(){
                if(count>0){
                   count--;
                adcount.innerHTML=count; 
            }else{
                adcount.innerHTML=0;
            }
       }
               
    }  
   
        child.onclick=function(){
                count1++;
                chcount.innerHTML=count1;
            chco.onclick=function(){
                if(count1>0){
                count1--;
                chcount.innerHTML=count1;  
                }else{
                chcount.innerHTML=0;
                }
            }         
                
        }
    }
  
   


小白自己寫的,可能有點簡單的複雜化了,還請各位多多包涵大笑