→●
カスタマイズされた組み込み要素は、それらが拡張する要素に基づいて、属性に関する通常の要件に従う。カスタム属性ベースの動作を追加するには、data-*属性を使用する。
HTML:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Simple word count web component</title> </head> <body> <h1>Word count rating widget</h1> <article contenteditable=""> <h2>Sample heading</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> <p>Pellentesque ornare tellus sit amet massa tincidunt congue.</p> <p is="word-count"></p> </article> <script src="main.js"></script> </body> </html>
JavaScript: main.js
// Create a class for the element class WordCount extends HTMLParagraphElement { constructor() { super(); function countWords(node){ const text = node.innerText || node.textContent; return text.split(/\s+/g).length; } const wcParent = this.parentNode; const count = `Words: ${countWords(wcParent)}`; const text = document.createElement('span'); text.textContent = count; // Create a shadow root const shadow = this.attachShadow({mode: 'open'}); shadow.appendChild(text); // Update count when element content changes setInterval(function() { const count = `Words: ${countWords(wcParent)}`; text.textContent = count; }, 200); } } // Define the new element customElements.define('word-count', WordCount, { extends: 'p' });
表示結果:
→net
表示内容: |
表示内容: |