自动轮播切换tab

一个项目中须要用到相似的功用,本身手写一个轮播切换,不足之处包涵。代码以下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .navUl{
            border: 1px solid #ddd;
            overflow: hidden;   
        }
        .navUl li{
            list-style: none;
            float: left;
            width: auto;
            height: 30px;
            line-height: 30px;
            padding: 0 10px;
            cursor: pointer;
        }
        .navUl li.activeLi{
            background: rgb(155, 155, 247);
            color: #fff;
        }
    </style>
</head>
<body>
    <ul class="navUl js-navUl">
        <li class="activeLi">tab1</li>
        <li>tab2</li>
        <li>tab3</li>
        <li>tab4</li>
        <li>tab5</li>
    </ul>
    <div>
        <div id="tabCon0">
                tab0内容
        </div>
        <div id="tabCon1" style="display:none">
                tab1内容
        </div>
        <div id="tabCon2" style="display:none">
                tab2内容
        </div>
        <div id="tabCon3" style="display:none">
                tab3内容
        </div>
        <div id="tabCon4" style="display:none">
                tab4内容
        </div>
    </div>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script>
        window.onload=function(){
            var autoTab = setInterval( changeTab,2000);
            $('.js-navUl').hover(
            function () {
                clearInterval(autoTab);
            }, 
            function () {
                autoTab = setInterval( changeTab,2000);
            });
            var tabIndex=0;
            function changeTab(){
                $(".js-navUl li").eq(tabIndex).addClass("activeLi").siblings().removeClass("activeLi");
                if($("#tabCon"+tabIndex)){
                    $("#tabCon"+tabIndex).show().siblings().hide();            
                }
                tabIndex++;
                if(tabIndex==5){
                    tabIndex=0;
                }
            }
            $(".js-navUl li").on("click",function(){
                var ind=$(this).index();
                if($("#tabCon"+ind)){
                    $("#tabCon"+ind).show().siblings().hide();            
                }
                if(ind!=4){
                    tabIndex=ind+1;            
                }else{
                    tabIndex=0;
                }
                $(this).addClass("activeLi").siblings().removeClass("activeLi");
            });
        }
    </script>
</body>
</html>

款式什么的本身修正即可

    原文作者:rocky191
    原文地址: https://segmentfault.com/a/1190000013471034
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞