tab切换

原创 978990968 随笔 原生js 164阅读 2018-03-14 19:16:43 举报

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>tab切换</title>
    <style>
        .demo{
            color:#666;
        }
        .demo-title{
            display:flex;
        }
        .title-item{
            width:20%;
            text-align: center;
            height:60px;
            line-height:60px;
            border:1px solid #333;
            cursor: pointer;
        }
        .demo-inner .inner-item{
            display:none;
        }
        .demo-inner .inner-item:nth-child(1){
            display:block;
        }
        .demo-title .title-item:nth-child(1){
            color:red;
        }
    </style>
</head>

<body>
    <div class='demo'>

         <div class="demo-title">
              <div class='title-item' data-num= '0'>title01</div>
              <div class='title-item' data-num= '1'>title02</div> 
              <div class='title-item' data-num= '2'>title03</div>
              <div class='title-item' data-num= '3'>title04</div>
         </div>
         <div class='demo-inner'>
             <div class='inner-item'>inner00000000000000001</div>
             <div class='inner-item'>inner00000000000000002</div>
             <div class='inner-item'>inner00000000000000003</div>
             <div class='inner-item'>inner00000000000000004</div>
         </div>

    </div>

</body>

</html>
<script>
// 获取绑定监听事件的元素
var ele = document.getElementsByClassName('demo-title')[0]
// 获取元素的切换标题项
var titEle = document.getElementsByClassName('title-item')
// 获取元素的切换内容项
var innerItem = document.getElementsByClassName('inner-item')
// 为元素绑定监听事件
ele.addEventListener('click',function(ev){
var eleTit = ev.target||ev.srcElement
// 获取自定义属性的下标
var cxNumber = parseInt(eleTit.getAttribute('data-num'))

     for(let i=0;i<innerItem.length;i++){
        innerItem[i].style.display='none'
        titEle[i].style.color='#666'
     }
     innerItem[cxNumber].style.display='block'
     titEle[cxNumber].style.color='red'
},false)

</script>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复