js排他思想和选项卡案例

js中排他思想个人理解为:
在监听成立时,要先把所有的同作用的样式清除,然后再设置需要的样式.

js排他思想和选项卡案例_第1张图片
js排他思想和选项卡案例_第2张图片
js排他思想和选项卡案例_第3张图片

在这个选项卡案例中,监听到鼠标悬停在导航上时,要遍历设置每一个导航下的内容显示为 none,然后再在悬停的具体导航的内容设置为 block,这就是排他思想的应用.

HTML:



    
    选项卡
    





CSS:
*{
    margin: 0;
    padding: 0;
    list-style: none;
}
a{
    text-decoration: none;
    color: #000;
}
#tab{
    width: 498px;
    height: 120px;
    border: 1px solid #cccccc;
    margin: 100px auto;
    overflow: hidden;
}
/*头部*/
#tab_header{
    background-color: #e8e8e8;
    height: 28px;
}
#tab_header ul{
    height: 100%;
    width: 500px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    line-height: 28px;
}
#tab_header ul li{
    width: 100px;
    text-align: center;
    border-bottom: 1px solid #cccccc;
    cursor: pointer;
}
#tab_header ul li:hover{
    font-weight: bold;
    color: orangered;
}
/*设置被选中的导航的样式*/
#tab_header ul li.selected{/*li与class之间必须无空格*/
    background-color: white;
    border-bottom: none;
    border-left: 1px solid #cccccc;
    border-right: 1px solid #cccccc;
}
/*设置第一个导航无左边框*/
#tab_header ul li:nth-child(1){
    border-left: none;
}
/*设置最后一个导航无右边框*/
#tab_header ul li:nth-last-child{
    border-right: none;
}
/*内容*/
#tab_content ul li{
    /*排版每一条内容*/
    float: left;
    width: 220px;
    text-align: center;
    margin: 10px;
}
/*按照导航组的单位来显示*/
#tab_content .group{
    display: none;
}
/*默认第一个导航的内容为显示*/
#tab_content .group:nth-child(1){
    display: block;
}
#tab_content ul li a:hover{
    color: orangered;
}
JS:
window.onload = function () {
    //封装获取对应id的元素的操作
    function $(id) {
        return typeof id === "string" ? document.getElementById(id) : null;
    }

    //获取导航列表
    var navList = $("tab_header").getElementsByTagName("li");
    //获取每组新闻列表
    var newsList = $("tab_content").getElementsByClassName("group");
    //遍历
    for (var i = 0; i <= navList.length; i++) {
        //传值处理同步异步
        var nNavList = navList[i];
        nNavList.index = i;
        //监听
        nNavList.onmouseover = function () {
            //监听成立时,排他思想,清除所有样式
            for (var j = 0; j < navList.length; j++) {
                newsList[j].style.display = "none";
                navList[j].className = "";
            }
            //设置具体样式
            this.className = "selected";
            newsList[this.index].style.display = "block";
        }
    }
}

你可能感兴趣的:(js排他思想和选项卡案例)