使用position: relative和@keyframes可实现元素偏移动画。先设置position: relative使元素保持布局稳定,再通过@keyframes定义动画关键帧,推荐使用transform: translateX()实现位移以提升性能,最后将动画绑定到元素上,设置动画名称、持续时间、速度曲线和重复次数等参数。例如让一个蓝色方块在原位置左右来回滑动,只需设置animation: slideRight 2s ease infinite alternate,其中slideRight定义从translateX(0)到translateX(150px)的位移变化。整个过程流畅且不影响页面布局。
使用 CSS 的 position: relative 与 @keyframes animation 可以轻松实现元素的偏移动画。关键在于通过相对定位控制元素在原有位置上的偏移,并结合动画规则让偏移量随时间变化。
1. 设置 relative 定位
要让元素能相对于自己原本的位置移动,先设置 position: relative。这样不会影响页面布局,同时允许你使用 top, right, bottom, left 来调整位置。
.moving-element { position: relative; }
2. 定义 @keyframes 动画
使用 @keyframes 定义动画的关键帧。比如从左边移动到右边,可以通过改变 left 或 transform: translateX() 实现。
@keyframes slideRight { from { left: 0; } to { left: 200px; } }
或者更推荐使用 transform,性能更好:
立即学习“前端免费学习笔记(深入)”;
@keyframes slideRight { from { transform: translateX(0); } to { transform: translateX(200px); } }
3. 应用 animation 属性
将定义好的动画绑定到元素上,设置持续时间、重复次数等参数。
.moving-element { position: relative; animation: slideRight 2s ease-in-out infinite; }
说明:
- slideRight:动画名称
- 2s:动画持续2秒
- ease-in-out:速度曲线
- infinite:无限循环
4. 完整示例
<div class="box">我会移动</div> <style> .box { width: 100px; height: 100px; background: blue; color: white; text-align: center; line-height: 100px; position: relative; animation: slideRight 2s ease infinite alternate; } @keyframes slideRight { 0% { transform: translateX(0); } 100% { transform: translateX(150px); } } </style>
这个例子中,蓝色方块会在原位置左右来回滑动。
基本上就这些。用 relative 保持布局稳定,再配合 animation 控制偏移,就能做出流畅的移动效果。注意优先使用 transform 而非 left/right,性能更优。