以后可能会用到 保存一下, 也顺便分享给有需要的人
先实现的是以方法形式实现的, 心情好的话封装个类出来
// 元素挂载style
export function styleList(dom: HTMLElement, styleList: object) {
for (let item in styleList) {
dom.style[item] = styleList[item];
}
}
// 元素挂载className
export function classNameList(dom: HTMLElement, className: Array<string>) {
dom.classList.add(...className)
}
// 绑定事件
export function bindMethods(dom: HTMLElement, methods: object) {
let keys = Object.keys(methods);
for (let i = 0; i < keys.length; i++) {
dom.addEventListener(keys[i], methods[keys[i]])
}
}
interface DomList {
tag: string, // 创建的tag名
innerText?: string, // tag中的innerText
className?: Array<string>, // tag类名
style?: object, // tag行内样式
children?: Array<DomList>, // tag子元素
methods?: object // tag绑定的事件
}
// 创建div的渲染函数
export function render(parentDom: HTMLElement | null, domList: DomList): HTMLElement {
let c_dom = document.createElement(domList.tag);
if (domList.innerText) {
c_dom.innerText = domList.innerText;
}
if (domList.className) {
classNameList(c_dom, domList.className);
}
if (domList.style) {
styleList(c_dom, domList.style);
}
if (domList.methods) {
bindMethods(c_dom, domList.methods);
}
if (domList.children && domList.children.length > 0) {
for (let i = 0; i < domList.children.length; i++) {
render(c_dom, domList.children[i]);
}
}
if (parentDom !== null) {
parentDom.append(c_dom);
return parentDom;
} else {
return c_dom;
}
}
调用方式
let test = render(null, {
tag: "div",
children: [
{
tag: "span",
innerText: "00:00",
style: {color: "red"},
methods: {
click: () => {
this.play()
}
}
},
{
tag: "span",
innerText: "10:00",
style: {color: "blue"},
methods: {
click: () => {
this.pause()
}
},
className: ["lll"],
children: [
{
tag: "span",
innerText: "这是弟中弟"
}
]
}
]
})