自定义html标签-tabs

101 阅读1分钟

<y-tabs>
  <y-tab active="true">1</y-tab>
  <y-tab>2</y-tab>
  <y-tab>3</y-tab>
</y-tabs>

class Tab extends HTMLElement {
  constructor() {
    super();
    this.shadow = this.attachShadow({mode: 'closed'});
    // 创建我们需要的标签
    this.container = document.createElement("ul");
    this.container.setAttribute("class","y-tabs-container")
    this.createTab();
    // 书写样式
    this.styleEl = document.createElement("style");
    let lStyleStr = ".y-tab-li { list-style-type: none;padding: 0 12px;cursor: pointer;} .y-tabs-container{display: flex;} .y-tab-active{border-bottom: 1px solid black;list-style-type: none;padding: 0 12px;cursor: pointer;}";
    this.styleEl.textContent = lStyleStr;
    // 将样式和dom元素挂载到页面
    this.shadow.appendChild(this.styleEl);
    this.shadow.appendChild(this.container);
  }
  createTab(){
    let tabs = this.childNodes;
    let tabId=0;
    tabs.forEach(tab=>{
      if(tab.nodeType === 1){
        let li = document.createElement("li");
        if(tab.getAttribute("active")){
          if(this.checked){
            throw new Error("active tab must be equal")
          }
          li.setAttribute("class","y-tab-active");
          this.checked = true;
        }else{
          li.setAttribute("class","y-tab-li");
        }
        li.setAttribute("id",tabId);
        li.innerText = tab.innerText;
        li.addEventListener("click",()=>{
          this.updateStatus();
          li.setAttribute("class","y-tab-active");
        })
        this.container.appendChild(li);
      }
    })
  }
  updateStatus(){
    let tabs = this.container.childNodes;
    tabs.forEach(tab=>{
      if(tab.nodeType === 1) {
        tab.setAttribute("class","y-tab-li");
      }
    })
  }
}

customElements.define('y-tabs', Tab);
````