07 use jquery to achieve tab tab to switch

1.1 Introduction

Here are ideas for implementing tab. In the implementation process, the first consideration is html structure, how to put the elements, in addition to through this place, whether through CSS style can achieve the effect we want. Finally, listening through js, when the tab to switch, we can hide all content, and then again to display the selected content to achieve the effect of switching.

1.2 The structure of the HTML
<div id="app">
    <ul id="tab-tilte" class="tab-tilte">
        <li class="active">标题一</li>
        <li>标题二</li>
        <li>标题三</li>
        <li>标题四</li>
    </ul>
    <div class="tab-content" id="tab-content">
        <div class="cur">内容一</div>
        <div>内容二</div>
        <div>内容三</div>
        <div>内容四</div>
    </div>
</div>
1.3 implement CSS style
<style type="text/css">
    ul li {

        margin: 0;
        padding: 0;
        list-style: none;
    }
    #app {
        width: 600px;
        height: 400px;
        margin: 0 auto;
        border: 1px solid #ccc;
    }
    .tab-tilte {
        width: 90%;
    }
    .tab-tilte li {
        float: left;
        width: 25%;
        padding: 10px 0;
        text-align: center;
        background-color: #f4f4f4;
        cursor: pointer;
    }
    /* 点击对应的标题添加对应的背景颜色 */
    .tab-tilte .active {

        background-color: #09f;
        color: #fff;
    }

    .tab-content div {

        float: left;
        width: 25%;
        line-height: 100px;
        text-align: center;
        display: none;
    }
    .tab-content div.cur{

        display: block;
    }
</style>

Show the effect of static (not dynamic efficiency):


11562297-2edc3b39bcdba7c7.png
image.png
Click to switch to achieve the introduction of jquery 1.4
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
  
    $(document).ready(function(){

        $('#tab-tilte li').click(function(){

           var cur=$(this).index(); //获取当前点击tab标题的索引值
            tabFun(cur);//调用方法
        });
    });

    function  tabFun(cur){
      
        $('#tab-tilte li').eq(cur).addClass('active').siblings().removeClass('active');
        $('#tab-content div').eq(cur).addClass('cur').siblings().removeClass('cur');

    }
</script>

The final display:


11562297-e4ae2b2a9362550a.png
image.png

Reproduced in: https: //www.jianshu.com/p/a31aceced140

Guess you like

Origin blog.csdn.net/weixin_33859665/article/details/91083217
Tab
Tab
Tab
Tab