js控制点击按钮样式切换!

html代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html lang="zh-CN">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>js控制按钮样式切换</title>  

<link href="css/my.css" rel="stylesheet">  

</head>  
<script type="text/javascript">  
//左边按钮的点击事件  
    window.onload = function(){  
        var arr = document.getElementsByTagName('button');  
        for(var i = 0;i<arr.length;i++){  
            arr[i].onclick = function(){      
                //this是当前激活的按钮,在这里可以写对应的操作    
                if(this.className == 'btn1'){  
                    this.className = 'btn2';  
                    var name = this.id;  
                    var btn = document.getElementsByClassName('btn2');  
                    for(var j=0;j<btn.length;j++){  
                        if(btn[j].id!=name){  
                            btn[j].className = 'btn1';  
                        }  
                    }     
                }  
             }   
         }  
     }  
</script>  
<body>  
    <div id="main" style="margin:auto 0">  
            <!--四个按钮-->  
            <div style="margin-top:2em;" align="center">  
              <div style="width:20%"><button id = "1" type = "button" class = "btn2"> 按钮1</button></div>  
              <div style="width:20%"><button  id = "2" type = "button" class = "btn1"> 按钮2</button></div>  
              <div style="width:20%"><button id = "3" type = "button" class = "btn1"> 按钮3</button></div>  
              <div style="width:20%"><button id = "4" type ="button" class = "btn1"> 按钮4</button></div>  
            </div>  
    </div>  

</body>  

</html>  

my.css


.btn1{
border:none;
height:3.5em;
background-color:#000000;
color:white;
font-size:1.2em;
margin-top:0.5em;
width:100%;
border-radius:1em;
}
.btn2{
border:none;
height:3.5em;
background-color:#3E8CD0;
color:white;
font-size:1.2em;
margin-top:0.5em;
width:100%;
border-radius:1em;
}

效果图:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值