#menu {
background-color: #f5f5f5;
}
.sub-menu,
.menu-item {
line-height: 30px;
text-indent: 10px;
}
.sub-menu {
padding-top: 30px;
position: relative;
transition: all 0.3s;
padding-left: 15px;
overflow-y: hidden;
}
.menu-item:hover {
background-color: gainsboro;
}
.sub-title {
background-color: #000;
color: #fff;
position: absolute;
top: 0;
left: 0;
width: 100%;
}
.sub-title:after {
content: '>';
transition: all 0.3s;
transform-origin: center;
position: absolute;
right: 10px;
margin-left: 15px;
width: 30px;
height: 30px;
line-height: 30px;
transform: rotate(90deg);
}
.sub-title-arrow-down:after {
transform: rotate(90deg);
}
.sub-title-arrow-right:after {
transform: rotate(0);
}
const arr = [{
"name": "前端",
"url": "/src/dist/docs/前端",
"child": [{
"name": "html",
"url": "/src/dist/docs/前端/html.html",
"child": []
}]
}, {
"name": "后端",
"url": "/src/dist/docs/后端",
"child": [{
"name": "nodejs",
"url": "/src/dist/docs/后端/nodejs.html",
"child": []
}]
}, {
"name": "文档",
"url": "/src/dist/docs/文档",
"child": [{
"name": "doc",
"url": "/src/dist/docs/文档/doc.html",
"child": []
}, {
"name": "文档",
"url": "/src/dist/docs/文档/文档.html",
"child": [{
"name": "文档1",
"url": "/src/dist/docs/文档/文档.html",
child: []
}, {
"name": "文档2",
"url": "/src/dist/docs/文档/文档.html",
child: [{
"name": "文档3",
"url": "/src/dist/docs/文档/文档.html",
child: []
},
{
"name": "文档4",
"url": "/src/dist/docs/文档/文档.html",
child: []
},
{
"name": "文档5",
"url": "/src/dist/docs/文档/文档.html",
child: []
},
]
}, ]
}]
}]
function renderMenu(arr) {
function renderMenuItem(data) {
let html = ''
data.forEach(item => {
if (!!item.child.length) {
html +=
`
`} else {
html += `
`}
})
return html
}
const html = renderMenuItem(arr)
const menu = document.querySelector('#menu')
menu.innerHTML = html
const subMenus = document.querySelectorAll('.sub-menu')
subMenus.forEach(item => {
const children = item.querySelectorAll('.menu-item, .sub-title')
item.style.height = (children.length - 1) * 30 + 'px';
const subTitle = item.querySelectorAll('.sub-title')
subTitle.forEach(v => {
v.onclick = function() {
const height = (children.length - 1) * 30 + 'px';
const isFold = parseInt(item.style.height) == 0
v.className = isFold ? 'sub-title sub-title-arrow-down' : 'sub-title sub-title-arrow-right'
item.style.height = isFold ? height : 0
}
})
})
}
renderMenu(arr)