实现类似andwalsh.com的自定义圆形悬浮光标(仅桌面端)
实现自定义桌面端光标效果(空心圆→链接悬浮实心圆)
核心思路
通过隐藏系统默认光标,创建跟随鼠标移动的自定义DOM元素,利用CSS切换样式实现空心/实心状态,同时通过媒体查询限制仅在桌面设备生效。
1. HTML结构
添加自定义光标元素和示例内容:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>自定义光标效果</title> <link rel="stylesheet" href="styles.css"> </head> <body> <!-- 自定义光标元素 --> <div class="custom-cursor"></div> <!-- 示例内容 --> <div class="content"> <h1>自定义光标演示</h1> <p>这是一段普通文本,光标显示为<span><a href="#">空心圆</a></span>。</p> <p>当你悬浮在<a href="#">这些链接</a>上时,光标会变成<span><a href="#">实心圆</a></span>。</p> </div> <script src="script.js"></script> </body> </html>
2. CSS样式
控制光标显示逻辑,默认隐藏系统光标,仅在桌面设备启用自定义光标:
/* 全局隐藏系统光标(仅在桌面设备生效) */ @media (hover: hover) and (pointer: fine) { body { cursor: none; } } /* 自定义光标基础样式 */ .custom-cursor { position: fixed; width: 24px; height: 24px; border: 2px solid #000; border-radius: 50%; pointer-events: none; /* 避免阻止底层元素交互 */ z-index: 9999; opacity: 0; transition: opacity 0.2s ease, background-color 0.2s ease; } /* 仅在桌面设备显示自定义光标 */ @media (hover: hover) and (pointer: fine) { .custom-cursor { opacity: 1; } } /* 链接悬浮时光标变为实心 */ .custom-cursor.active { background-color: #000; }
3. JavaScript逻辑
实现光标跟随鼠标移动,以及链接悬浮时的样式切换:
const customCursor = document.querySelector('.custom-cursor'); const links = document.querySelectorAll('a'); // 光标跟随鼠标移动 document.addEventListener('mousemove', (e) => { // 减去宽高一半,让光标中心对齐鼠标位置 const left = e.clientX - customCursor.offsetWidth / 2; const top = e.clientY - customCursor.offsetHeight / 2; customCursor.style.left = `${left}px`; customCursor.style.top = `${top}px`; }); // 链接悬浮时切换光标样式 links.forEach(link => { link.addEventListener('mouseenter', () => { customCursor.classList.add('active'); }); link.addEventListener('mouseleave', () => { customCursor.classList.remove('active'); }); });
关键细节说明
- 媒体查询:
@media (hover: hover) and (pointer: fine)确保仅在支持hover操作、且使用精准指针(如鼠标)的设备上启用自定义光标,自动排除触控屏设备。 - pointer-events: none:避免自定义光标元素阻止底层链接或按钮的点击事件。
- 过渡动画:添加
transition属性让光标样式切换更平滑,接近目标网站的体验。
内容的提问来源于stack exchange,提问作者Penelope Atkinson
相关产品推荐
相关产品推荐

