前端基础(四十二):非固定高度的容器实现折叠面板效果

发布于:2025-09-07 ⋅ 阅读:(21) ⋅ 点赞:(0)

效果展示

在这里插入图片描述

源码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<style>
    p {
        margin: 0;
    }

    .card {
        width: 300px;
        box-shadow: 0 0 0 1px red;

        .card-header {
            height: 32px;
            padding: 0 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 0 0 1px red;
        }

        .card-content {
            max-height: 0;
            transition: max-height 0.5s ease;
            overflow: hidden;

            article {
                padding: 10px 16px;
            }
        }
    }
</style>

<body>
    <div class="card">
        <header class="card-header">
            <span>展开/收缩</span>
            <button id="toggle-button">&gt;</button>
        </header>
        <main id="content" class="card-content">
            <article id="article">
            </article>
        </main>
    </div>

    <script>
        const content = document.querySelector('#content');

        // 模拟动态内容加载
        const article = document.querySelector('#article');
        setInterval(() => {
            article.appendChild(document.createElement('p')).innerText = '动态添加的内容';
        }, 1000);

        // 点击按钮切换展开/收缩
        const button = document.querySelector('#toggle-button');
        button.addEventListener('click', () => {
            const isExpanded = content.style.maxHeight;
            if (isExpanded) {
                content.style.maxHeight = null; // 收缩
            } else {
                content.style.maxHeight = content.scrollHeight + "px";
            }
        });

        // 监测内容变化(例如,添加/删除节点)
        const observer = new MutationObserver(() => {
            if (content.style.maxHeight) {
                content.style.maxHeight = content.scrollHeight + "px"; // 更新高度
            }
        });

        // 配置观察器以监测内容变化
        observer.observe(content, {
            childList: true,
            subtree: true,
            characterData: true
        });
    </script>
</body>

</html>

网站公告

今日签到

点亮在社区的每一天
去签到