<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#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);
}
</style>
</head>
<body>
<div id="menu"></div>
<script>
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 +=
`<div class="sub-menu"><div class="sub-title">${item.name}</div>${renderMenuItem(item.child)}</div>`
} else {
html += `<div class="menu-item">${item.name}</div>`
}
})
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)
</script>
</body>
</html>
原生js折叠菜单栏
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...