万户资源科技
万汇资源微信公众号

微信扫码有惊喜!

用jQuery实现栏目切换

luping 2015-12-24 技术

使用jQuery实现栏目切换,点击栏目即可切换同级栏目。

代码如下:

<style>
*{ margin:0; padding:0; list-style:none;}
body{ font-size:12px;}

#menu{width:360px; overflow:hidden; margin:100px auto;border:1px solid #0166AC;}
#menu #nav {display:block;width:100%;padding:0;margin:0;list-style:none;}
#menu #nav li {float:left;width:120px;}
#menu #nav li a {display:block;line-height:27px;text-decoration:none;padding:0 0 0 5px; text-align:center; color:#333;}
#menu_con{ width:358px; height:135px; border-top:none}
.tag{ padding:10px; overflow:hidden;}
.selected{background:#0166AC; color:#fff;}
</style>
</head>
<body>

<!--代码部分begin-->
<div id="menu">
<!--tag标题-->
    <ul id="nav">
        <li><a href="#" class="selected">栏目一</a></li>
        <li><a href="#" class="">栏目二</a></li>
        <li><a href="#" class="">栏目三</a></li>
    </ul>
<!--二级菜单-->
    <div id="menu_con">
        <div class="tag" style="display:block">
            内容一
         </div> 
        <div class="tag" style="display:none">
            内容二   
         </div> 
        <div class="tag"  style="display:none">
            内容三
        </div> 
</div>
</div>
<script>
var tabs=function(){
    function tag(name,elem){
        return (elem||document).getElementsByTagName(name);
    }
    //获得相应ID的元素
    function id(name){
        return document.getElementById(name);
    }
    function first(elem){
        elem=elem.firstChild;
        return elem&&elem.nodeType==1? elem:next(elem);
    }
    function next(elem){
        do{
            elem=elem.nextSibling;  
        }while(
            elem&&elem.nodeType!=1  
        )
        return elem;
    }
    return {
        set:function(elemId,tabId){
            var elem=tag("li",id(elemId));
            var tabs=tag("div",id(tabId));
            var listNum=elem.length;
            var tabNum=tabs.length;
            for(var i=0;i<listNum;i++){
                    elem[i].onclick=(function(i){
                        return function(){
                            for(var j=0;j<tabNum;j++){
                                if(i==j){
                                    tabs[j].style.display="block";
                                    //alert(elem[j].firstChild);
                                    elem[j].firstChild.className="selected";
                                }
                                else{
                                    tabs[j].style.display="none";
                                    elem[j].firstChild.className="";
                                }
                            }
                        }
                    })(i)
            }
        }
    }
}();
tabs.set("nav","menu_con");//执行
</script>

实现效果如图:


--597


文章关键词
tab切换
jQuery切换
tab标签
qq qq tel
服务热线:

134-1954-9128