代码如下:<!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>选项卡切换</title></head><body> <my-tabs index=“0” titles="[‘首页’,‘核心产品’,‘项目案例’]" contents="[’<h1>公司地址:</h1><article>公司位于四川省成都市武侯区XX街道</article>’,’<h2>核心的产品1</h2><p>XXAPP是为XXX公司服务二产生的</p>’,’<a href=https://www.iviewui.com/ target=_blank>项目地址</a>’]"> </my-tabs> <script> function ewEval(str) { return new Function(‘return ’ + str)(); } class MyTabs extends HTMLElement { constructor() { super(); const shadom = this.attachShadow({ mode: “open” }); let count = ewEval(this.getAttribute(‘index’)) || 0, tabTitles = ewEval(this.getAttribute(’titles’)) || [‘标签一’, ‘标签二’, ‘标签三’], tabContent = ewEval(this.getAttribute(‘contents’)) || [‘标签一的内容’, ‘标签二的内容’, ‘标签三的内容’], title_len = tabTitles.length, content_len = tabContent.length; let header = document.createElement(‘header’); for (let i = 0; i < title_len; i++) { let buttons = document.createElement(‘button’); buttons.innerHTML = tabTitles[i]; if (count === i) buttons.classList.add(‘active’); buttons.onclick = function () { let curIndex = tabTitles.indexOf(this.textContent); let _buttons = shadom.querySelectorAll(‘button’), _divs = shadom.querySelectorAll(‘div’); for (let j = 0,len = _buttons.length; j < len; j++) { if (curIndex !== j) { _buttons[j].classList.remove(‘active’); _divs[j].classList.remove(‘active’); } _buttons[curIndex].classList.add(‘active’); _divs[curIndex].classList.add(‘active’); } } header.appendChild(buttons); } shadom.appendChild(header); for (let _i = 0; _i < content_len; _i++) { let divs = document.createElement(‘div’); divs.innerHTML = tabContent[_i]; if (count === _i) divs.classList.add(‘active’); shadom.appendChild(divs); } let style = document.createElement(‘style’); style.textContent = header{ border-bottom:1px solid #dcdee2; height:35px; } button{ outline:none; cursor:pointer; color:#515a6e; margin-left:15px; font-size:14px; transition:color .2s linear,border-bottom .2s linear; background-color:transparent; padding:0 13px; height:35px; display:inline-block; border:none; } a{ text-decoration:none; color:#515a6e; } a:hover,a:active{ color:#2196ff; } button.active{ color:#2196ff; border-bottom:1px solid #2192ff; } div{ display:none; padding:13px 0; } div.active{ display:block; }; shadom.appendChild(style); } } customElements.define(‘my-tabs’, MyTabs); </script></body></html>你可以狠狠点击此处具体示例查看效果。这里还可以进行优化。