<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>web組件</title> </head> <body> <dry-card name="test" image="https://www.baidu.com/img/bd_logo1.png"></dry-card> <template id="dryCardTemplate"> <style> :host { background-color: red; } .button { padding: 10px; } </style> <div> <h3></h3> <p><img src="" width="270" height="129"></p> <p><button class="button">肯定</button></p> </div> </template> <script> class dryCard extends HTMLElement{ constructor(){ super(); var shadow = this.attachShadow({mode: 'closed'}); var content = document.getElementById('dryCardTemplate').content.cloneNode(true); content.querySelector('h3').innerText = this.getAttribute('name'); content.querySelector('img').setAttribute('src', this.getAttribute('image')); shadow.appendChild(content); shadow.querySelector('button').addEventListener('click', function(){ console.log("click"); }); } }; window.customElements.define('dry-card', dryCard); </script> </body> </html>