按钮点击切换

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .Box{
            width: 240px;
            border: 1px solid #000;
            margin:100px auto;
            padding:20px;
        }
        .con{
            width: 100%;
            height: 200px;
            background-color: #cccccc;
            border: 1px solid #000;
            margin-top:10px;
            display:none;
        }
        .current{
            background-color: pink;
        }
    </style>
</head>
<body>
<div class="Box" id="box">
    <button class="current" >按钮1</button>
    <button >按钮2</button>
    <button>按钮3</button>
    <button>按钮4</button>
    <!-- <div class="con" style="display:block">内容1</div>
    <div class="con">内容2</div>
    <div class="con">内容3</div>
    <div class="con">内容4</div> -->
</div>
<script>



    // 首先要获得所有的按钮
    var box = document.getElementById('box');
    var btns = document.getElementsByTagName('button');
	var divs = box.getElementsByTagName('div');
	
	// console.log(btns.length);

    for(var i=0;i<btns.length;i++){
        var btn = btns[i];
        // btn.index = i;// 给每个按钮添加一个自定义属性,用来存储当前的索引
        btn.onclick = function(){

            for(var j=0;j<btns.length;j++){
                btns[j].className = '';
            }
			this.className = 'current';
			
            // for(var k = 0;k<divs.length;k++){
            //     divs[k].style.display = 'none';
            // }
            // divs[this.index].style.display = 'block';
        }
    }
</script>
</body>
</html>

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值