class MyTab extends HTMLElement{ //创建一个类名MyTab
constructor(){ //构造函数
super(); //指向父类构造函数,必须要有的 const shadow = this.attachShadow({ //影子dom
mode : 'open' //开放的封装模式
}) let n = 0;
let titles = ['标题1','标题2','标题3'];
let inners = ['内容1','内容2','内容3']; for(let i=0;i<3;i++){
let button = document.createElement('button');
button.innerHTML = titles[i]; if(i == n){
button.classList.add('active');
} button.onclick = function () {
let aButton = shadow.querySelectorAll('button');
let aP = shadow.querySelectorAll('p'); for(let i=0;i<3;i++){
aButton[i].classList.remove('active');
aP[i].classList.remove('active');
}
this.classList.add('active');
aP[i].classList.add('active');
} shadow.appendChild(button);
} for(let i=0;i<3;i++){
let p = document.createElement('p');
p.innerHTML = inners[i]; if(i == n){
p.classList.add('active');
} shadow.appendChild(p);
} const style = document.createElement('style'); style.textContent = `
button.active{
background : yellow;
}
p{
display:none;
}
p.active{
display:block;
}
`; shadow.appendChild(style); let div = document.createElement('div'); //插槽
div.innerHTML = '<slot></slot>'; shadow.appendChild(div); }
} customElements.define('my-tab',MyTab); //注册组件
然后在html文件里面写入<my-tab></my-tab>就可以使用组件了