使用原生js創建自定義標簽
阿新 • • 發佈:2019-02-05
inline img pac 技術分享 shadow line fault () 代碼
使用原生js創建自定義標簽
效果圖
代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div style="height: 100px;"></div> <popup-info img="img/alt.png" text="提示信息"> </body> <script> class PopUpInfo extends HTMLElement { constructor() { super(); // 創建文本框 var info = document.createElement(‘span‘); info.setAttribute(‘class‘, ‘info‘); // 獲取自定義標簽的text屬性 var text = this.getAttribute(‘text‘); info.textContent = text; // 創建圖片元素 var imgUrl; if (this.hasAttribute(‘img‘)) { imgUrl = this.getAttribute(‘img‘); } else { imgUrl = ‘img/default.png‘; } var img = document.createElement(‘img‘); img.src = imgUrl; var icon = document.createElement(‘span‘); icon.setAttribute(‘class‘, ‘icon‘); icon.appendChild(img); // 創建css樣式 var style = document.createElement(‘style‘); style.textContent = ` .wrapper { position: relative; } .info { font-size: 0.8rem; width: 200px; display: inline-block; border: 1px solid black; padding: 10px; background: white; border-radius: 10px; opacity: 0; transition: 0.6s all; position: absolute; bottom: 20px; left: 10px; z-index: 3; } img { width: 1.2rem; } .icon:hover + .info, .icon:focus + .info { opacity: 1; } ` // 創建根元素,作用其實是將分離的css和html聚合起來 var shadow = this.attachShadow({ mode: ‘open‘ }); // 創建一個span標簽包裹內容 var wrapper = document.createElement(‘span‘); wrapper.setAttribute(‘class‘, ‘wrapper‘); // 將創建的style節點追加到影子節點中 shadow.appendChild(style); // 依次將html按照層級關系添加 shadow.appendChild(wrapper); wrapper.appendChild(icon); wrapper.appendChild(info); } } // 定義組件 customElements.define(‘popup-info‘, PopUpInfo); </script> </html>
使用原生js創建自定義標簽