js tab栏切换

今天我们制作一个tab栏切换废话不多说直接上代码

下面是css样式

  *{
                margin: 0;
                padding: 0;
                text-decoration: none;
            }
            .nav a{
                width: 180px;
                height: 35px;
                display: block;
                float: left;
                color: #fff;
                background-color: #999;
                text-align: center;
                line-height: 35px;
                margin-right: 15px;
            }
            .nav .hover{
                background-color: blue;
            }
            .nav_con>div:nth-child(1){
                width: 570px;
                height: 300px;
                background-color: red;
                display: none;
                clear: both;
            }
            .nav_con>div:nth-child(2){
                width: 570px;
                height: 300px;
                background-color: greenyellow;
                display: none;
                clear: both;
            }
            .nav_con>div:nth-child(3){
                width: 570px;
                height: 300px;
                background-color: pink;
                display: none;
                clear: both;
            }
            
            .nav_con>div:first-child{
                display: block;
            }

上面的是一些样子可以凭自己喜好编写样式

下面是html的代码

  <div class="tab">
        <div class="nav">
            <a href="#" class="hover">公司新闻</a>
            <a href="#">行业资讯</a>
            <a href="#">公司详情</a>
         </div>
         <div class="c"></div>
         <div class="nav_con">
             <div class="a">公司新闻内容</div>
             <div>行业资讯内容</div>
             <div>公司详情内容</div>
         </div>
       </div>

接下来是js代码简单易懂

 <script>
            var navs = document.querySelectorAll(".nav a");
            var thisindex = 0;
            var nav_cons = document.querySelectorAll(".nav_con>div");
               //给每一项添加点击事件和加上自定义属性index
                for(var i=0;i<navs.length;i++){
               //给每一项 加上index索引
                 navs[i].setAttribute("index",i);
               //点击事件
                navs[i].onclick = function(){
                 //当nav 导航点击的时候 给全局thisindex赋值 
                  thisindex = this.getAttribute("index");
                 for(var j =0;j<navs.length;j++){
                    navs[j].className="";  //去除所有的hover样式 
                    nav_cons[j].style.display = "none";   //让所有的tab 页内容隐藏     
                 }
                 this.className="hover";
                 nav_cons[thisindex].style.display ="block"; //让所有的tab 页内容显示 
             }
            }
          
       </script>

这样就写好了

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值