欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > js实现可折叠的列表或菜单

js实现可折叠的列表或菜单

2025/7/16 12:09:51 来源:https://blog.csdn.net/weixin_44134816/article/details/148405231  浏览:    关键词: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时,通过一系列计算和判断,确定一个合适的折叠位置,并将该位置信息存储在组件的状态中,以便后续使用。这种逻辑通常用于实现可折叠的列表或菜单,以优化页面布局和提升用户体验。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com