js实现滑入滑出
滑入滑出效果实现方法
滑入滑出效果可以通过CSS过渡(transition)或JavaScript动画实现。以下是两种常见的实现方式:

使用CSS过渡和类切换
通过添加/移除类名触发CSS过渡效果,适合简单场景。

// 获取元素
const element = document.getElementById('target');
// 滑入
function slideIn() {
element.style.display = 'block';
setTimeout(() => {
element.classList.add('active');
}, 10);
}
// 滑出
function slideOut() {
element.classList.remove('active');
setTimeout(() => {
element.style.display = 'none';
}, 500); // 与过渡时间一致
}
// 对应CSS
#target {
display: none;
transform: translateX(-100%);
transition: transform 0.5s ease;
}
#target.active {
transform: translateX(0);
}
使用requestAnimationFrame
更精细控制动画过程,适合复杂动画需求。
function slide(element, direction, duration = 500) {
const start = performance.now();
const from = direction === 'in' ? -element.offsetWidth : 0;
const to = direction === 'in' ? 0 : -element.offsetWidth;
element.style.transform = `translateX(${from}px)`;
element.style.display = 'block';
function animate(time) {
const elapsed = time - start;
const progress = Math.min(elapsed / duration, 1);
const current = from + (to - from) * progress;
element.style.transform = `translateX(${current}px)`;
if (progress < 1) {
requestAnimationFrame(animate);
} else if (direction === 'out') {
element.style.display = 'none';
}
}
requestAnimationFrame(animate);
}
使用Web Animations API
现代浏览器支持的动画API,性能较好。
function slideWithWAAPI(element, direction) {
const keyframes = [
{ transform: `translateX(${direction === 'in' ? '-100%' : '0'})` },
{ transform: `translateX(${direction === 'in' ? '0' : '-100%'})` }
];
const options = {
duration: 500,
easing: 'ease-in-out',
fill: 'forwards'
};
if (direction === 'in') {
element.style.display = 'block';
}
const animation = element.animate(keyframes, options);
animation.onfinish = () => {
if (direction === 'out') {
element.style.display = 'none';
}
};
}
注意事项
- 性能优化:优先使用CSS动画,硬件加速属性如transform和opacity
- 浏览器兼容:老旧浏览器可能需要polyfill
- 可访问性:确保动画不影响用户体验,可提供关闭选项
- 移动端适配:考虑触摸事件和响应式设计
以上方法可根据具体需求选择,CSS过渡方案最简单,WAAPI方案最现代,requestAnimationFrame提供最大控制权。






