js实现可折叠的列表或菜单
setCollapse() {
//初始展开数值
const ref = this.$refs.listItemContentRef
if(!ref || !ref.children) return;
let len = ref.children.length
if(ref.clientHeight > 77 && ref.children.length > 3) {
const offsetTop = ref.children[0].offsetTop
const maxHeight = 77 + offsetTop
const collapseTotal = [];
collapseTotal.push(this.collapseTotal[0])
collapseTotal.push(this.collapseTotal[1])
for(let i=2;i<len;i++) {
if(ref.children[i].offsetTop >= maxHeight){
const i_1_clientWidth= ref.children[i-1].clientWidth
const i_1_offsetLeft= ref.children[i-1].offsetLeft
const pcw = ref.clientWidth
const collapse_w = 38
const pcwDiff = pcw - (i_1_offsetLeft + i_1_clientWidth);
if (pcwDiff > collapse_w) {
collapseTotal[0] = i;
} else if (i_1_clientWidth + pcwDiff > collapse_w) {
collapseTotal[0] = i - 1;
} else {
collapseTotal[0] = i - 2;
}
this.collapseTotal=collapseTotal
break;
}
}
}
},
这段代码的核心功能是根据父容器的高度和子元素的布局情况,动态计算并更新一个列表的折叠点。当列表的高度超过一定阈值(77像素)且子元素数量大于3时,通过一系列计算和判断,确定一个合适的折叠位置,并将该位置信息存储在组件的状态中,以便后续使用。这种逻辑通常用于实现可折叠的列表或菜单,以优化页面布局和提升用户体验。