js实现slideup

实现 SlideUp 动画效果
使用 JavaScript 实现元素的 slideUp 动画效果可以通过操作元素的 height 和 overflow 属性来实现。以下是几种常见的方法:
使用原生 JavaScript
function slideUp(element, duration = 300) {
element.style.height = element.offsetHeight + 'px';
element.style.transition = `height ${duration}ms ease`;
element.offsetHeight; // 触发重绘
element.style.height = '0';
element.style.overflow = 'hidden';
setTimeout(() => {
element.style.display = 'none';
}, duration);
}
使用 CSS 动画
function slideUp(element, duration = 300) {
element.style.animation = `slide-up ${duration}ms forwards`;
// 定义 CSS 动画
const style = document.createElement('style');
style.textContent = `
@keyframes slide-up {
from { height: ${element.offsetHeight}px; }
to { height: 0; }
}
`;
document.head.appendChild(style);
setTimeout(() => {
element.style.display = 'none';
document.head.removeChild(style);
}, duration);
}
使用 jQuery 风格实现
function slideUp(element, duration = 300) {
const el = element;
el.style.transitionProperty = 'height, margin, padding';
el.style.transitionDuration = duration + 'ms';
el.style.boxSizing = 'border-box';
el.style.height = el.offsetHeight + 'px';
el.offsetHeight;
el.style.overflow = 'hidden';
el.style.height = '0';
el.style.paddingTop = '0';
el.style.paddingBottom = '0';
el.style.marginTop = '0';
el.style.marginBottom = '0';
window.setTimeout(() => {
el.style.display = 'none';
el.style.removeProperty('height');
el.style.removeProperty('padding-top');
el.style.removeProperty('padding-bottom');
el.style.removeProperty('margin-top');
el.style.removeProperty('margin-bottom');
el.style.removeProperty('overflow');
el.style.removeProperty('transition-duration');
el.style.removeProperty('transition-property');
}, duration);
}
使用 requestAnimationFrame 实现平滑动画
function slideUp(element, duration = 300) {
const startHeight = element.offsetHeight;
const startTime = performance.now();
function animate(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const height = startHeight * (1 - progress);
element.style.height = height + 'px';
element.style.overflow = 'hidden';
if (progress < 1) {
requestAnimationFrame(animate);
} else {
element.style.display = 'none';
element.style.height = '';
element.style.overflow = '';
}
}
requestAnimationFrame(animate);
}
注意事项
- 确保目标元素最初是可见的(
display不为none) - 动画过程中可能需要处理
padding和margin以确保视觉效果一致 - 对于现代浏览器,CSS transitions 通常是性能最佳的选择
- 如果需要反向操作(slideDown),需要保存原始高度或计算内容高度
这些方法可以根据具体需求进行调整,例如添加回调函数、支持 Promise 等。







