原理: 自定义标签是通过定义class类继承HTMLElement实现的, class特性是ECMAScript6中引入的特性, ES6以下没有这个特性
class 不是新的对象继承模型,它只是原型链的语法糖表现形式。可以通过改写适配ES6以下特性
<html> <head> <meta charset="utf-8"> <title>Angular 2 实例 - 菜鸟教程(runoob.com)</title> </head> <body> <!-- 自定义标签必须在class之前, 否则类中的getAttribute无法获取到自定义标签的值;如果放在class后面,则不需要带任何属性,就算带了也获取不了 --> <popup-info img="1.gif" text1="haha"></popup-info> <popup-info img="1.gif" text1="aaaaa"></popup-info> <script> class PopUpInfo extends HTMLElement {
constructor () {
super(); // 在此定义自定义标签 我顶一个icon和text并列的 // Create a shadow root let shadow = this.attachShadow({
mode: 'closed'}); // 创建我们需要的标签 let wrapper = document.createElement("div"); let iconBox = document.createElement("div"); let textBox = document.createElement("div"); // 为标签添加样式 wrapper.setAttribute("class","wrapper"); iconBox.setAttribute("class","icon"); textBox.setAttribute("class","text"); let text = this.getAttribute("text1"); // 获取标签里面传递的值 textBox.textContent = "text"; let imgUrl; if(this.hasAttribute("img")) {
imgUrl = this.getAttribute("img"); } else {
imgUrl = "default.gif"; // 设置一个默认图片 } var img = document.createElement("img"); img.src = imgUrl; iconBox.appendChild(img); // 书写样式 var style = document.createElement("style"); let lStyleStr = ".wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}" lStyleStr += ".icon {margin-right: 10px; width: 50px; height: 50px;}" lStyleStr += ".icon img { width: 100%; height: 100%;}" lStyleStr += ".text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}" style.textContent = lStyleStr; // 将样式和dom元素挂载到页面 shadow.appendChild(style); shadow.appendChild(wrapper); wrapper.appendChild(iconBox); wrapper.appendChild(textBox); } } customElements.define('popup-info', PopUpInfo); </script> </body> </html>
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222277.html原文链接:https://javaforall.net
