自定义简单的 html 标签

自定义简单的 html 标签

最近在学微信小程序,编写界面(.wxml 文件)需要用到 WX小程序官方提供的组件,比如 viewtext 等等

幸运的是,讲视频的老师讲了 自定义标签,借助这个可以理解 wx小程序的组件原理、element-ui 的 el- 开头的标签的实现原理

自定义标签

  1. js 文件中定义集成 HTMLElement 的子类,重写 constructor 方法
  2. 使用 customElements.define() 绑定标签
  3. 在 html 中引入 js 文件,使用标签。

可以简单实现

  1. 自定义标签
  2. 自定义属性

  1. 页面

  2. 页面元素

简单实现

<body>

  <tag-demo>没有定义的tag。</tag-demo>

  <br />

  <my-tag red>red text.</my-tag>
  <my-tag>black text.</my-tag>

  <br />

  <my-code>int[] nums = new int[10];</my-code>
  <my-code>synchronized</my-code>

</body>
<script src="customTag.js"></script>

class MyTag extends HTMLElement {
  constructor() {
    super();
    if (this.hasAttribute("red")) {// 如果 my-tag 有 red 属性
      this.setAttribute("class", "myTagStyle");// 给 my-tag 定义 class = myTagStyle
      var style = document.createElement("style");// 创建 style
      style.textContent = ".myTagStyle{ color:red; }";// 向其中添加 .myTagStyle 样式
      document.head.append(style);// 酱 style 标签加入 dom.head 中。
    }
  }
}

customElements.define('my-tag', MyTag);

/**
 * “优化”:只用第一个 style 标签用来存放各种自定义标签的属性
 *  - 解析 style。
 *  - 判断 & 添加属性。
 */

// 获取 head.style 标签
function getHeadsStyle() {
  var res = document.head.getElementsByTagName('style')
  var style;
  if (res.length == 0) {
    style = document.createElement('style');
  } else {
    style = res[0];
  }
  return style;
}

class MyCodeBlock extends HTMLElement {
  constructor() {
    super();
    this.clazzName = "codeBlockStyle";// 属性=>类名
    this.setAttribute('class', this.clazzName);
    var style = getHeadsStyle();
    if (style.textContent.indexOf(this.clazzName) == -1) {//没有此属性则添加
      style.textContent += " .codeBlockStyle { font-size: 16px; color: #a04515;   font-family: 'Lucida Console', 'Courier New', monospace; } "
    }
  }
}

customElements.define('my-code', MyCodeBlock);

posted @ 2021-10-02 12:23  egu0o  阅读(1327)  评论(0编辑  收藏  举报