用js实现transition
使用 CSS 和 JavaScript 实现过渡效果
在 JavaScript 中实现 CSS 的 transition 效果,可以通过直接操作元素的样式或类名来触发过渡。以下是几种常见方法:
直接修改内联样式
通过 JavaScript 动态修改元素的 style 属性,结合 CSS 中定义的 transition 属性实现过渡效果。

<style>
.box {
width: 100px;
height: 100px;
background: red;
transition: all 0.5s ease;
}
</style>
<div class="box"></div>
<script>
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.style.width = '200px';
box.style.backgroundColor = 'blue';
});
</script>
通过切换类名触发过渡
通过添加或移除类名触发 CSS 中定义的过渡效果。

<style>
.box {
width: 100px;
height: 100px;
background: red;
transition: all 0.5s ease;
}
.box.active {
width: 200px;
background: blue;
}
</style>
<div class="box"></div>
<script>
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.classList.toggle('active');
});
</script>
使用 requestAnimationFrame 实现动画
对于更复杂的过渡效果,可以通过 requestAnimationFrame 逐帧修改属性。
const box = document.querySelector('.box');
let width = 100;
function animate() {
width += 1;
box.style.width = `${width}px`;
if (width < 200) {
requestAnimationFrame(animate);
}
}
box.addEventListener('click', animate);
使用 Web Animations API
现代浏览器支持 Web Animations API,可以直接通过 JavaScript 定义动画。
const box = document.querySelector('.box');
box.addEventListener('click', () => {
box.animate([
{ width: '100px', backgroundColor: 'red' },
{ width: '200px', backgroundColor: 'blue' }
], {
duration: 500,
easing: 'ease'
});
});
注意事项
- 性能优化:优先使用 CSS
transition或transform,硬件加速性能更好。 - 兼容性:Web Animations API 在旧浏览器中可能需要 polyfill。
- 事件监听:过渡结束后可通过
transitionend事件触发回调。
box.addEventListener('transitionend', () => {
console.log('过渡完成');
});






