js实现transition
实现 CSS Transition 效果的 JavaScript 方法
在 JavaScript 中实现 CSS 的 transition 效果,可以通过直接操作元素的样式或类名来触发过渡动画。以下是几种常见方法:
直接修改内联样式
通过 JavaScript 修改元素的 style 属性,同时确保 CSS 中已定义 transition 属性:
const element = document.getElementById('target');
element.style.transition = 'all 0.5s ease'; // 设置过渡属性
element.style.width = '200px'; // 触发过渡
通过类名切换实现
CSS 中预定义过渡样式,通过 JavaScript 切换类名触发动画:
/* CSS 部分 */
.box {
width: 100px;
height: 100px;
background: blue;
transition: all 0.5s ease;
}
.box.active {
width: 200px;
background: red;
}
// JavaScript 部分
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.classList.toggle('active');
});
使用 Web Animation API
现代浏览器支持的原生动画 API,可实现更复杂的控制:
const element = document.getElementById('target');
element.animate(
[
{ transform: 'translateX(0px)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0.5 }
],
{
duration: 1000,
easing: 'ease-in-out',
fill: 'both'
}
);
动态创建样式规则
通过 JavaScript 动态插入 CSS 规则实现过渡效果:
const style = document.createElement('style');
style.textContent = `
.dynamic-transition {
transition: transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
}
`;
document.head.appendChild(style);
const btn = document.getElementById('animate-btn');
btn.classList.add('dynamic-transition');
btn.style.transform = 'scale(1.2)';
注意事项
- 确保过渡属性在样式变化前已定义
- 硬件加速考虑:对
opacity和transform属性的过渡性能更优 - 过渡结束事件可通过
transitionend事件监听:
element.addEventListener('transitionend', () => {
console.log('Transition completed');
});
高级控制技巧
对于需要精细控制的场景,可以结合 requestAnimationFrame:

function animate() {
const start = performance.now();
const duration = 1000;
function frame(time) {
const progress = (time - start) / duration;
if (progress < 1) {
element.style.opacity = progress;
requestAnimationFrame(frame);
} else {
element.style.opacity = 1;
}
}
requestAnimationFrame(frame);
}






