自定義簡單的 html 標簽
最近在學微信小程序,編寫界面(.wxml
文件)需要用到 WX小程序官方提供的組件,比如 view
、text
等等
幸運的是,講視頻的老師講了 自定義標簽,借助這個可以理解 wx小程序的組件原理、element-ui 的 el-
開頭的標簽的實現原理
自定義標簽
- js 文件中定義集成
HTMLElement
的子類,重寫constructor
方法 - 使用
customElements.define()
綁定標簽 - 在 html 中引入 js 文件,使用標簽。
可以簡單實現
- 自定義標簽
- 自定義屬性
-
頁面
-
頁面元素
簡單實現
<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);