Home >Web Front-end >JS Tutorial >Cartoon Network Logo with Web Component
Since I was a kid, I've loved the classic Cartoon Network Logo.
I created a Custom HTML Element to make text like it with different colors.
class CartoonNetworkify extends HTMLElement { // respond to color updates static observedAttributes = ['color1','color2']; constructor() { super(); } connectedCallback() { let words = this.innerText.split(' '); this.attachShadow({mode:'open'}); var root = this.shadowRoot; var table = document.createElement('table'); // longest word length let maxLength = words.reduce((max,w, i)=> w.length > max ? w.length: max, Number.MIN_VALUE); // default black & white var color1 = this.getAttribute('color1') || 'black'; var color2 = this.getAttribute('color2') || 'white'; words.reduce((tbody,line,i,words)=>{ // pad for extra space line = line.padEnd(maxLength); let trow = line.split('').reduce((trow,letter,j)=>{ // create cells let td = trow.insertCell(); td.innerText = letter.toUpperCase(); let odd = i%2 == j%2; td.dataset.odd = odd; td.style.backgroundColor=odd?color1:color2; td.style.color = odd?color2:color1; return trow; }, tbody.insertRow()); return tbody; }, table.createTBody()); root.append(table); // add style from template let template = document.getElementById('cartoon-networkify-template'); root.append(template.content.cloneNode(true)); } // update attributes later attributeChangedCallback(name,oldValue, newValue) { if(this.shadowRoot) { this.shadowRoot.querySelectorAll('td').forEach((td)=> { var odd = td.dataset.odd == 'true'; if(name=='color1') { td.style[odd?'backgroundColor':'color'] = newValue ; } else if(name == 'color2') { td.style[odd?'color':'backgroundColor'] = newValue ; } }); } } }
Please feel free to ask me any questions.
To know more about custom elements, visit MDN.
The above is the detailed content of Cartoon Network Logo with Web Component. For more information, please follow other related articles on the PHP Chinese website!