js实现多tab栏切换效果(二)

时间:2022-11-30 12:05:14

上篇js实现tab栏切换效果(一)实现了tab栏的切换效果,如果实现多tab栏的切换效果的话,直接用上面的代码会有小bug。不过不用怕,给每个tab栏加一个id唯一标识的话,就没啥问题了。
废话上说,上代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css"> *{ margin: 0; padding: 0; } ul{list-style: none;} .box{ width: 370px; height: 300px; margin: 100px auto; border: 1px solid #ccc; overflow: hidden; } .bt span{ display: inline-block; width: 80px; height: 30px; background-color: pink; padding: 3px; text-align: center; line-height: 30px; cursor: pointer; } .bt span.current{ background-color: purple; } .bc li{ width: 100%; height: 270px; background-color: purple; display: none; } .bc li.show{ display: block; } </style>
        <script type="text/javascript"> window.onload=function(){ function fun(obj){ // 获取每个tab栏的id var target = document.getElementById(obj); var spans = target.getElementsByTagName("span"); var lis = target.getElementsByTagName("li"); for (var i=0;i<spans.length;i++) { spans[i].index=i; spans[i].onmouseover= function(){ for (var j=0;j<spans.length;j++) { spans[j].className=""; lis[j].className=""; } this.className="current"; lis[this.index].className = "show"; } } } fun("news"); fun("fruits"); fun("clothes"); } </script>
    </head>
    <body>
        <div class="box" id="news">
            <div class="bt">
                <span class="current">新闻</span>
                <span>娱乐</span>
                <span>科技</span>
                <span>经济</span>
            </div>
            <div class="bc">
                <ul>
                    <li class="show">新闻内容</li>
                    <li>娱乐内容</li>
                    <li>科技内容</li>
                    <li>经济内容</li>
                </ul>
            </div>
        </div>
        <div class="box" id="fruits">
            <div class="bt">
                <span class="current">苹果</span>
                <span>香蕉</span>
                <span>橘子</span>
                <span>雪梨</span>
            </div>
            <div class="bc">
                <ul>
                    <li class="show">苹果酸甜</li>
                    <li>香蕉香香</li>
                    <li>橘子好棒</li>
                    <li>雪梨脆脆</li>
                </ul>
            </div>
        </div>
        <div class="box" id="clothes">
            <div class="bt">
                <span class="current">运动装</span>
                <span>休闲装</span>
                <span>礼服装</span>
                <span>乞丐装</span>
            </div>
            <div class="bc">
                <ul>
                    <li class="show">运动棒棒</li>
                    <li>正好休闲</li>
                    <li>礼服靓靓</li>
                    <li>正合心意</li>
                </ul>
            </div>
        </div>
    </body>
</html>

实现效果:
js实现多tab栏切换效果(二)