1. 程式人生 > 其它 >JavaScript原生動態切換tab樣式

JavaScript原生動態切換tab樣式

技術標籤:JavaScriptjavascriptjquery

在這裡插入圖片描述

<style>
    .box {
        display: flex;
        width: 500px;
        justify-content: space-between;
        border: 1px solid darkgray;
        align-items: center;
        height: 60px;
    }

    .box div {
        text-align: center;
    }

    .active {
color: red; font-weight: bold; } </style> <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script> <script> $(function () { let titleList = ['音樂', '電影', '娛樂', '動畫']; let html = ''; let index = 0;//預設顯示樣式div
let divList = []; //切換資料 function setTabBar(arr) { arr.forEach(function (item) { html += '<div>' + item + '</div>' }); $('.box').html(html); divList = $('.box>div'); divList[index].className =
'active'; } setTabBar(titleList); //div點選事件切換樣式,切換卡片 for (let i = 0; i < divList.length; i++) { divList[i].onclick = function () { divList[index].className = ''; divList[i].className = 'active'; index = i; } } }) </script> <body> <div> <div class="box"> </div> </div>