js实现图片浮动
实现图片浮动效果
使用JavaScript实现图片浮动效果可以通过CSS动画或动态修改样式属性完成。以下是几种常见方法:
使用CSS动画结合JavaScript
定义CSS关键帧动画,通过JavaScript控制动画的启停或参数:

.float-animation {
animation: float 3s ease-in-out infinite;
}
@keyframes float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-20px); }
}
const image = document.getElementById('floating-image');
image.classList.add('float-animation');
动态修改transform属性
通过定时器动态修改图片的垂直位置:

const image = document.getElementById('floating-image');
let position = 0;
let direction = 1;
function floatImage() {
position += 0.1 * direction;
if (position > 10) direction = -1;
if (position < -10) direction = 1;
image.style.transform = `translateY(${position}px)`;
requestAnimationFrame(floatImage);
}
floatImage();
使用GSAP库实现高级浮动
GSAP库提供更流畅的动画控制:
gsap.to("#floating-image", {
y: -20,
duration: 2,
repeat: -1,
yoyo: true,
ease: "sine.inOut"
});
响应鼠标移动的浮动效果
实现图片随鼠标移动产生浮动效果:
const image = document.getElementById('floating-image');
document.addEventListener('mousemove', (e) => {
const x = e.clientX / window.innerWidth - 0.5;
const y = e.clientY / window.innerHeight - 0.5;
image.style.transform = `translate(${x * 20}px, ${y * 20}px)`;
});
注意事项
- 性能优化:使用
transform代替top/left定位,避免重排 - 移动端适配:触摸事件需替换鼠标事件
- 动画平滑度:优先使用
requestAnimationFrame而非setInterval - 内存管理:移除事件监听器避免内存泄漏






