JavaScript tab bar switching effect

Time:2021-1-12

Code implementation:

Document
    
        * {
            margin: 0;
            padding: 0;
        }
        
        li {
            list-style-type: none;
        }
        
        .tab {
            width: 978px;
            margin: 100px auto;
        }
        
        .tab_list {
            height: 39px;
            border: 1px solid #ccc;
            background-color: #f1f1f1;
        }
        
        .tab_list li {
            float: left;
            height: 39px;
            line-height: 39px;
            padding: 0 20px;
            text-align: center;
            cursor: pointer;
        }
        
        .tab_list .current {
            background-color: #c81623;
            color: #fff;
        }
        
        .item_info {
            padding: 20px 0 0 20px;
        }
        
        .item {
            display: none;
        }
    



    
        
            
                Product introduction
                Specifications and packaging
                After sale guarantee
                Commodity evaluation (50000)
                Mobile community
            
        
        
            
                Product introduction模块内容
            
            
                Specifications and packaging模块内容
            
            
                After sale guarantee模块内容
            
            
                Commodity evaluation (50000)模块内容
            
            
                Mobile community模块内容
            

        
    
    
        //Get element
        var tab_list = document.querySelector('.tab_list');
        var lis = tab_list.querySelectorAll('li');
        var items = document.querySelectorAll('.item');
        //For loop binding click event
        for (var i = 0; i < lis.length; i++) {
            //Start setting index numbers for 5 li 
            lis[i].setAttribute('index', i);
            lis[i].onclick = function() {
                //1. On the module tab, click one, the current background color will be red, and the rest will not change (exclusive thinking) the way to modify the class name

                //Clear styles from other tabs
                for (var i = 0; i < lis.length; i++) {
                    lis[i].className = '';
                }
                //Set your own style individually 
                this.className = 'current';

                //2. The following display content module
                var index = this.getAttribute('index');
                //Let the rest of the items be hidden
                for (var i = 0; i < items.length; i++) {
                    items[i].style.display = 'none';
                }
                //Let the corresponding item be displayed
                items[index].style.display = 'block';
            }
        }