js实现滑进滑出效果
使用CSS Transition实现滑进滑出
通过CSS的transition属性和transform或margin变化实现平滑滑动效果。需定义初始状态和结束状态的样式,通过JavaScript切换类名触发动画。
<style>
.box {
width: 100px;
height: 100px;
background: blue;
transition: transform 0.5s ease;
transform: translateX(-100%);
}
.box.active {
transform: translateX(0);
}
</style>
<div class="box"></div>
<button onclick="toggleSlide()">切换</button>
<script>
function toggleSlide() {
document.querySelector('.box').classList.toggle('active');
}
</script>
使用CSS Animation实现滑动
通过@keyframes定义动画关键帧,结合JavaScript动态添加动画类。适合需要更复杂动画路径的场景。

<style>
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes slideOut {
from { transform: translateX(0); }
to { transform: translateX(-100%); }
}
.slide-in { animation: slideIn 0.5s forwards; }
.slide-out { animation: slideOut 0.5s forwards; }
</style>
<div id="box" style="width:100px;height:100px;background:red;"></div>
<button onclick="playAnimation()">播放</button>
<script>
let isIn = false;
function playAnimation() {
const box = document.getElementById('box');
box.className = isIn ? 'slide-out' : 'slide-in';
isIn = !isIn;
}
</script>
使用Web Animations API
现代浏览器支持的底层API,可直接通过JavaScript控制动画。提供更精细的动画控制能力。

const box = document.getElementById('box');
box.animate([
{ transform: 'translateX(0)' },
{ transform: 'translateX(100px)' }
], {
duration: 500,
fill: 'forwards'
});
使用GSAP库实现高级滑动
GSAP提供更强大的动画控制,支持缓动函数、时间轴等高级特性。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
<div id="box" style="width:100px;height:100px;background:green;"></div>
<button onclick="gsapSlide()">滑动</button>
<script>
function gsapSlide() {
gsap.to("#box", {
x: 100,
duration: 0.5,
ease: "power2.inOut"
});
}
</script>
响应式滑动效果实现
结合窗口大小检测,实现自适应滑动距离的效果。使用window.innerWidth计算动态滑动距离。
function responsiveSlide() {
const distance = window.innerWidth * 0.8;
document.getElementById('box').style.transform = `translateX(${distance}px)`;
}






