js实现图片上下浮动
使用 CSS 动画实现图片上下浮动
通过 CSS 的 @keyframes 和 transform 属性可以实现平滑的上下浮动效果。JavaScript 仅用于动态控制动画的启停或参数调整。
.floating-image {
animation: float 3s ease-in-out infinite;
}
@keyframes float {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
}
<img src="image.jpg" class="floating-image">
通过 JavaScript 动态控制浮动
使用 requestAnimationFrame 实现更灵活的浮动控制,适合需要实时调整参数的场景。
const img = document.querySelector('img');
let position = 0;
let direction = 1;
const speed = 0.05;
const range = 20;
function animate() {
position += speed * direction;
if (position > range || position < 0) direction *= -1;
img.style.transform = `translateY(${position}px)`;
requestAnimationFrame(animate);
}
animate();
结合 CSS 变量实现可配置浮动
通过 JavaScript 动态修改 CSS 变量,实现运行时调整浮动幅度和速度。
.floating-image {
animation: float var(--float-duration) ease-in-out infinite;
--float-range: 20px;
--float-duration: 3s;
}
@keyframes float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(var(--float-range)); }
}
document.documentElement.style.setProperty('--float-range', '30px');
document.documentElement.style.setProperty('--float-duration', '2s');
使用第三方库实现高级效果
GSAP 等动画库可提供更复杂的浮动效果,如弹性运动或轨迹控制。
gsap.to(".floating-image", {
y: -20,
duration: 2,
repeat: -1,
yoyo: true,
ease: "sine.inOut"
});
性能优化建议
对于多元素浮动,优先使用 CSS 方案。需要交互控制的场景可使用 transform 代替 top/bottom 定位以获得硬件加速。动态创建的浮动元素建议使用 CSS 类而非行内样式。







