如何实现鼠标悬停时链接随光标固定距离跟随的吸引效果?
实现鼠标悬停时链接跟随光标固定距离的效果
嘿,我之前研究过类似的光标跟随链接效果,给你一步步拆解实现方法,完全能复刻你说的那种右下角"Follow Us"的交互!
1. 基础HTML结构
先搭好最核心的元素:触发悬停的按钮,以及要跟随光标的链接容器
<!-- 右下角的触发按钮 --> <div class="follow-trigger">Follow Us</div> <!-- 跟随光标的链接容器 --> <div class="cursor-follow-link"> <a href="#">Instagram</a> <a href="#">Twitter</a> </div>
2. CSS样式设置
给元素加上定位和基础美化,重点是控制触发按钮的固定位置,以及跟随元素的隐藏/定位规则
/* 触发按钮:固定在右下角 */ .follow-trigger { position: fixed; bottom: 20px; right: 20px; padding: 12px 18px; background-color: #222; color: #fff; border-radius: 6px; cursor: pointer; transition: background-color 0.2s ease; } .follow-trigger:hover { background-color: #444; } /* 跟随链接容器:默认隐藏,绝对定位 */ .cursor-follow-link { position: absolute; display: none; gap: 8px; padding: 10px 14px; background-color: #fff; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.15); pointer-events: none; /* 关键:让鼠标事件穿透,避免干扰触发按钮的hover状态 */ } .cursor-follow-link a { color: #222; text-decoration: none; font-size: 14px; } .cursor-follow-link a:hover { text-decoration: underline; }
3. JavaScript交互逻辑
核心是监听鼠标的进入、移动、离开事件,控制链接的显示/隐藏,以及实时更新链接的位置
const triggerBtn = document.querySelector('.follow-trigger'); const followLink = document.querySelector('.cursor-follow-link'); // 定义链接和光标之间的固定偏移量(可根据需求调整) const OFFSET_X = 15; const OFFSET_Y = 15; // 鼠标进入触发按钮时,显示链接并开始监听鼠标移动 triggerBtn.addEventListener('mouseenter', () => { followLink.style.display = 'flex'; document.addEventListener('mousemove', updateLinkPosition); }); // 鼠标离开触发按钮时,隐藏链接并停止监听 triggerBtn.addEventListener('mouseleave', () => { followLink.style.display = 'none'; document.removeEventListener('mousemove', updateLinkPosition); }); // 实时更新链接的位置,保持和光标固定距离 function updateLinkPosition(e) { // 计算链接的坐标:光标位置 + 偏移量 const linkLeft = e.clientX + OFFSET_X; const linkTop = e.clientY + OFFSET_Y; // 可选:处理边界溢出,避免链接超出视口 if (linkLeft + followLink.offsetWidth > window.innerWidth) { followLink.style.left = `${e.clientX - followLink.offsetWidth - OFFSET_X}px`; } else { followLink.style.left = `${linkLeft}px`; } if (linkTop + followLink.offsetHeight > window.innerHeight) { followLink.style.top = `${e.clientY - followLink.offsetHeight - OFFSET_Y}px`; } else { followLink.style.top = `${linkTop}px`; } }
额外优化小技巧
- 给跟随链接加过渡动画:在
.cursor-follow-link里加transition: all 0.1s ease;,让链接移动更顺滑自然 - 如果需要多组跟随链接,只要复制结构并修改选择器即可
- 可以根据需求调整偏移量
OFFSET_X和OFFSET_Y,控制链接在光标上下左右的位置
内容的提问来源于stack exchange,提问作者Zorkzyd




