如何为多个元素调用函数,纯js

rryofs0p  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(189)

我正在尝试构建一个具有选项卡式内容功能的多元素系统。如何对var中声明的多个元素使用同一个函数?e、 g.克隆具有类似内容但ID和区域标签不同的父div.tabs元素;不要介意css ts仅用于片段视觉效果

const tab = document.querySelector('.tabs');    
        const tabButtons = tab.querySelectorAll('[role="tab"]');
        const tabPanels = Array.from(tab.querySelectorAll('[role="tabpanel"]'));

        function tabClickHandler(e) {
            //Hide All Tabpane
            tabPanels.forEach(panel => {
                panel.hidden = 'true';
            });

            //Deselect Tab Button
            tabButtons.forEach( span => {
                span.setAttribute('aria-selected', 'false');
            });

            //Mark New Tab
            e.currentTarget.setAttribute('aria-selected', 'true');

            //Show New Tab
            const { id } = e.currentTarget;

            const currentTab = tabPanels.find(
                panel => panel.getAttribute('aria-labelledby') === id
            );

            currentTab.hidden = false;
        }

        tabButtons.forEach(span => {
            span.addEventListener('click', tabClickHandler);
        });
/* Tabs Styling */
    .tabs [role="tablist"] > h3 {
        cursor: pointer;
    }
    .tabs [role="tablist"] > h3[aria-selected="true"] {
        color: #4fcbf2;
    }
    .tabs [role="tabpanel"] p {
        position: absolute;
        background-color: #eff1f2;
        padding: 1.8em 2.2em;
    }
    .wp-block-columns {
        display: flex;
        margin-bottom: 1.75em;
        flex-wrap: wrap;
        gap: 1em;
    }
    .wp-block-columns {
        flex-wrap: nowrap;
    }
    .wp-block-column {
        flex-basis: 0;
        flex-grow: 1;
    }
<div class="tabs wp-block-columns">
<div class="wp-block-column" role="tablist" aria-label="contractors">
    <h3 class="has-normal-font-size" role="tab" aria-selected="true" id="contractors-1">Do you have a limited company that you want to use for international contracting but don't know how?</h3>
    <h3 class="has-normal-font-size" role="tab" aria-selected="false" id="contractors-2">Do you want to work abroad but are not satisfied with the retentions that</h3>
</div>
<div class="tabcontent wp-block-column">
    <div role="tabpanel" aria-labelledby="contractors-1"><p>Access Tax and Accounting is a firm of accountants that specialises in this fields</p></div>
    <div role="tabpanel" aria-labelledby="contractors-2" hidden=""><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus semper</p></div>
</div>
</div>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题