原生js、jQuery实现选项卡功能

在大家在网上平常浏览网页的时候,想必各位都会看到选项卡功能,在这里给大家详解一下用原生js、jQuery如何来写一些基本的选项卡

话不多说,先给各位看一下功能图:

                 

好了,下边开始写代码了:

HTML代码:

<ul>
    <li class="click">red</li>
    <li>blue</li>
    <li>yellow</li>
</ul>
<div class="box">
    <div class="show"></div>
    <div></div>
    <div></div>
</div>

CSS代码:

*{
    margin: 0;
    padding: 0;
}
ul{
    overflow: hidden;
    /*注意父级元素塌陷,详情见博客*/
}
ul li{
    width: 100px;
    height: 30px;
    float: left;
    border: 1px solid #000;
    list-style: none;
    border-right: none;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
}
ul li:last-child{
    border-right: 1px solid #000000;
}
.box{
    position: relative;
}
.box div{
    width: 304px;
    height: 300px;
    position: absolute;
    display: none;
}
.box div:first-child{
    background-color: red;
}
.box div:nth-child(2){
    background-color: blue;
}
.box div:last-child{
    background-color: yellow;
}
.box .show{
    display: block;
}
.box .hide{
    display: none;
}
.click{
    background-color: #ccc;
}
基本样式的设置

原生JS写法:

var liAll = document.querySelectorAll('li');//获取要操作的元素
var divAll = document.querySelectorAll('.box div');//获取被操作的跟随元素
for (var i = 0;i<liAll.length;i++) { //for循环为每一个元素添加点击事件
    liAll[i].index = i;    //作用域的问题,如果for循环使用let声明,则不需要该行代码
    liAll[i].onclick = function () { 
        for (var j = 0;j<liAll.length;j++) {
            liAll[j].className = "";//将所有被操作的元素的背景色消失
            divAll[j].className = "hide";//将所有被操作的元素全部隐藏
        }
        this.className = "click";//当前被点击的元素背景色改变
        divAll[this.index].className = "show";//将所有被操作的元素跟随显示
    }
}

jQuery写法:

引入jQuery文件 网址:https://www.bootcdn.cn/jquery/

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
$("li").each(function  (index , ele) {//each循环遍历。得到所有的li  index代表li的下表,ele元素
    $(this).click(function () {//$(this) 表示当前点击的元素
        $(this).addClass("click");
        $(this).siblings().removeClass("click");
        $(".box div:eq("+index+")").css({"display":"block"}); //eq  根据each循环得出index的所引值  取对应的div显示
        $(".box div:eq("+index+")").siblings().css({"display":"none"}); //对应的div隐藏
    });
});

如果您有看不明白的地方,可以留言,咱们共同交流!

前端知识更新的很快,继续努力吧!

猜你喜欢

转载自www.cnblogs.com/qdclub/p/9750614.html