console
class Item {
static isStyleInit = false;
constructor(options) {
this.el = document.createElement('div');
this.el.classList.add('menu-item');
this.wrapInner = document.createElement('span');
this.wrapInner.classList.add('wrapInner');
this.el.appendChild(this.wrapInner);
this.options = options;
this.init();
}
init() {
this.optionsInit();
this.styleInit();
}
optionsInit() {
let o = this.options;
this.wrapInner.textContent = o.label;
this.listenersInit();
}
listenersInit() {
let ls = this.options.listeners;
let that = this;
for (let key in ls) {
let lt = ls[key];
lt.forEach(function (item) {
that.el.addEventListener(key, item);
});
}
}
styleInit() {
if (!this.constructor.isStyleInit) {
let style = [
{
selector: ".menu-item",
cssText: `
position: relative;
color: red;
overflow: hidden;
padding: 3px 10px;
`
}
]
style.forEach(item => {
let last = document.styleSheets.length - 1;
document.styleSheets[last].addRule(item.selector, item.cssText);
});
this.constructor.isStyleInit = true;
}
}
}
class ItemList {
static isStyleInit = false;
constructor(template) {
this.container = document.createElement('div');
this.container.classList.add('item-list');
this.template = template;
this.items = [];
this.init();
}
init() {
this.styleInit();
this.traversal(template);
}
styleInit() {
if (!this.constructor.isStyleInit) {
let style = [];
style.forEach(item => {
let last = document.styleSheets.length - 1;
document.styleSheets[last].addRule(item.selector, item.cssText);
});
this.constructor.isStyleInit = true;
}
}
traversal(array) {
for (let key in array) {
let i = array[key];
let item = new Item(i);
this.items.push(item);
this.container.appendChild(item.el);
}
}
}
class Menu {
static isStyleInit = false;
constructor(place, template) {
this.container = document.createElement('div');
this.container.classList.add('Menu');
this.place = place;
this.template = template;
this.init();
}
init() {
this.styleInit();
this.deepTraversal(template);
}
styleInit() {
if (!this.constructor.isStyleInit) {
let style = [];
style.forEach(item => {
let last = document.styleSheets.length - 1;
document.styleSheets[last].addRule(item.selector, item.cssText);
});
this.constructor.isStyleInit = true;
}
}
deepTraversal(template) {
}
}
let template = [
{
label: "文件",
listeners: {
click: [
function () {
console.log(1);
},
]
}
},
{
label: "编辑"
},
{
label: "运行"
},
{
label: "帮助"
},
]
let menu = new Menu(template);
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=, initial-scale=">
<meta http-equiv="X-UA-Compatible" content="">
<title></title>
</head>
<body>
<div id="nav">
<div class="menu-item">111</div>
</div>
</body>
</html>
* {
margin: 0;
padding: 0;
}