js实现过渡
使用 CSS transition 属性实现过渡效果
在 JavaScript 中可以通过修改元素的 CSS 属性来实现过渡效果,结合 CSS 的 transition 属性
通过修改元素的 class 或直接设置 style 来触发过渡:

const element = document.getElementById('myElement');
element.style.transition = 'all 0.3s ease';
element.style.width = '200px';
使用 Web Animations API
现代浏览器支持 Web Animations API,可以直接用 JavaScript 创建和控制动画:
const element = document.getElementById('myElement');
element.animate([
{ opacity: 0 },
{ opacity: 1 }
], {
duration: 1000,
easing: 'ease-in-out'
});
使用 requestAnimationFrame 实现自定义过渡
对于需要更精细控制的过渡效果,可以使用 requestAnimationFrame:

function animate({ duration, timing, draw }) {
let start = performance.now();
requestAnimationFrame(function animate(time) {
let timeFraction = (time - start) / duration;
if (timeFraction > 1) timeFraction = 1;
const progress = timing(timeFraction);
draw(progress);
if (timeFraction < 1) {
requestAnimationFrame(animate);
}
});
}
animate({
duration: 1000,
timing: function(timeFraction) {
return timeFraction;
},
draw: function(progress) {
element.style.width = progress * 100 + 'px';
}
});
使用 CSS 类切换实现过渡
通过添加/移除 CSS 类来触发过渡效果:
.box {
transition: all 0.3s ease;
}
.box.active {
transform: scale(1.2);
background-color: #ff0000;
}
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.classList.toggle('active');
});
使用 GSAP 动画库
GSAP 是一个专业的 JavaScript 动画库,可以实现复杂的过渡效果:
gsap.to(".box", {
duration: 1,
x: 100,
rotation: 360,
ease: "bounce.out"
});






