本文最后更新于:2 years ago
简介
html
标签由标签名称
标签属性
内部标签组成
,通过这一特征可以将标签元素转换成js代码,如下代码所示:
const dom = {
type: 'div', // 标签名称
props: { // 标签属性
class: 'container',
style: 'color:red'
},
children: [ // 内部标签
{
type: 'span',
props: {
style: 'color:blue'
},
children: 'hello world' // 出口内容
}
]
}
通过将上述的js代码使用递归的方式生成对应的dom元素。
递归函数
const mapVDomsToDoms = (doms) => {
// 生成dom元素
const oDom = document.createElement(doms?.type);
// 添加标签属性
if (doms?.props) {
Object.keys(doms.props).forEach(prop => {
oDom.setAttribute(prop, doms.props[prop]);
})
}
// 添加内容标签元素
if (doms?.children instanceof Arrary) {
doms.children.forEach(child => {
oDom.appendChild(mapVDomsToDoms(child));
})
}else {
// 递归出口,children为text内容
oDom.innerText = doms.children;
}
return oDom;
}
页面测试
通过编写js标签内容生成对应的dom元素,并渲染到页面中
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!