js实现收缩
实现元素收缩的 JavaScript 方法
使用 CSS transition 与 height 属性
通过动态调整元素的 height 属性实现平滑收缩效果。初始状态需设置固定高度,收缩时改为 0 并配合 overflow: hidden。

const element = document.getElementById('target');
element.style.transition = 'height 0.3s ease';
element.style.height = `${element.scrollHeight}px`;
// 收缩函数
function collapse() {
element.style.height = '0';
}
利用 classList.toggle 切换 CSS 类
预定义收缩样式的 CSS 类,通过 JavaScript 动态切换类名。

.collapsed {
height: 0;
overflow: hidden;
transition: height 0.3s;
}
document.getElementById('toggleBtn').addEventListener('click', () => {
document.getElementById('target').classList.toggle('collapsed');
});
使用 requestAnimationFrame 实现逐帧动画
适用于需要更精细控制的场景,逐帧减少高度值。
function animateCollapse(element, duration = 300) {
const startHeight = element.scrollHeight;
const startTime = performance.now();
function updateHeight(time) {
const elapsed = time - startTime;
const progress = Math.min(elapsed / duration, 1);
element.style.height = `${startHeight * (1 - progress)}px`;
if (progress < 1) {
requestAnimationFrame(updateHeight);
}
}
requestAnimationFrame(updateHeight);
}
注意事项
- 确保目标元素具有
overflow: hidden属性,防止内容溢出影响动画效果。 - 若元素包含内边距或边框,需通过
box-sizing: border-box保证高度计算准确。 - 对于动态内容,收缩前需通过
scrollHeight获取实际高度。
扩展方案:水平方向收缩
将 height 替换为 width 属性即可实现水平收缩效果,原理相同。
element.style.transition = 'width 0.3s';
element.style.width = '200px';
function collapseHorizontal() {
element.style.width = '0';
}






