2018-11-08 js/jquery原生实现tab选项卡功能

分享下我自己用jquery(也可以换成js原生,只是写法有些许区别)手写的tab选项卡功能的demo
主要思想就是给每个按钮及每个tab都加上一个下标用于使其一一对应,如:

按钮[i] --> tab[j] (只有 i 等于 j 的时候按钮对应的tab才会显示出来)

html:

这是第一个tab

这是第二个tab

这是第三个tab

js:

var btns = $(".changebtn");

var tabs = $(".tab");

console.log(btns.length)

for(var i = 0;i < btns.length; i++){

    var btn = btns[i];

    btn.index = i;

    console.log(btn.index);

    for(var k = 0;k

        tabs[k].style.display = 'none';

    }

    btn.onclick = function () {

        for(var j = 0; j < tabs.length; j++){

            var oo = tabs[j];

            tabs.currentIndex = j;

        }

        tabs.css('display','none');

        tabs[this.index].style.display = 'block';

    }

}

css:(随便写的,方便区分tab块)

.changebtn{

    width: 60px;

    height: 30px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    background-color: #01AAED;

    color: #fff;

    border: none;

}

.tab{

    margin-top: 20px;

    width: 160px;

    line-height: 60px;

    text-align: center;

    background-color: red;

}

.tab1{

    background-color: yellow;

}

.tab3{

    background-color: green;

}

效果图:


2018-11-08 js/jquery原生实现tab选项卡功能_第1张图片
2018-11-08 js/jquery原生实现tab选项卡功能_第2张图片

你可能感兴趣的:(2018-11-08 js/jquery原生实现tab选项卡功能)