js实现跟随
实现跟随效果的JavaScript方法
使用JavaScript实现跟随效果可以通过监听鼠标移动事件或触摸事件,动态更新目标元素的位置。以下是几种常见方法:
监听鼠标移动事件
通过mousemove事件获取鼠标坐标,并将目标元素的left和top样式属性设置为鼠标位置:
document.addEventListener('mousemove', function(e) {
const follower = document.getElementById('follower');
follower.style.left = e.clientX + 'px';
follower.style.top = e.clientY + 'px';
});
平滑跟随效果

为让跟随更自然,可以使用缓动动画效果,逐渐缩小目标与鼠标之间的距离:
let posX = 0, posY = 0;
const follower = document.getElementById('follower');
document.addEventListener('mousemove', function(e) {
posX = e.clientX;
posY = e.clientY;
});
function animate() {
const followerX = parseFloat(follower.style.left || 0);
const followerY = parseFloat(follower.style.top || 0);
const dx = posX - followerX;
const dy = posY - followerY;
follower.style.left = followerX + dx * 0.1 + 'px';
follower.style.top = followerY + dy * 0.1 + 'px';
requestAnimationFrame(animate);
}
animate();
跟随旋转或缩放

通过计算距离或角度,可以实现更复杂的跟随效果,比如旋转或缩放:
document.addEventListener('mousemove', function(e) {
const follower = document.getElementById('follower');
const rect = follower.getBoundingClientRect();
const centerX = rect.left + rect.width / 2;
const centerY = rect.top + rect.height / 2;
const angle = Math.atan2(e.clientY - centerY, e.clientX - centerX);
follower.style.transform = `rotate(${angle}rad)`;
});
跟随触摸事件
在移动设备上,可以使用touchmove事件实现类似效果:
document.addEventListener('touchmove', function(e) {
const follower = document.getElementById('follower');
follower.style.left = e.touches[0].clientX + 'px';
follower.style.top = e.touches[0].clientY + 'px';
});
注意事项
- 确保目标元素使用
position: absolute或position: fixed定位。 - 避免频繁的DOM操作,使用
transform属性优化性能。 - 考虑边界情况,防止元素超出可视区域。






