效果展示

源码
<!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">></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>