TAG
CSS
JavaScript
Result
Run
License
<button type="button" id="btn-add">ADD</button>
.container { width: 300px; height: 200px; margin: auto; border: 1px solid #FF0000; overflow: auto; } .container> p { width: 600px; }
class Square extends HTMLElement { static get observedAttributes() { return ['w','h','bg','r']; } constructor() { super(); const shadow = this.attachShadow({ mode: 'open' }); const div = document.createElement("div"); const style = document.createElement("style"); shadow.appendChild(style); shadow.appendChild(div); } connectedCallback() { this.initStyle(); } attributeChangedCallback(name, oldValue, newValue) { this.initStyle(); } initStyle() { const shadow = this.shadowRoot; shadow.querySelector("style").textContent = ` div { width: ${this.getAttribute('w')}px; height: ${this.getAttribute('h')}px; background-color: ${this.getAttribute('bg')}; border-radius: ${this.getAttribute('r')}px; } `; } } customElements.define('custom-square', Square); window.addEventListener("load", () => { const btnAdd = document.querySelector("#btn-add"); btnAdd.onclick = function() { let square = document.createElement('custom-square'); square.setAttribute('w', '100'); square.setAttribute('h', '100'); square.setAttribute('bg', '#FF0000'); square.setAttribute('r', '30'); document.body.appendChild(square); }; });
Console
expand_less
License
License
by DevDic
Close