求助:实现随div内鼠标位置变化的自定义光标及幻灯片序号引用
实现随鼠标位置变化的自定义光标及幻灯片序号显示
我来帮你拆解这个需求的实现步骤,一步步搞定这个效果:
1. 先搞定基础的自定义跟随光标
首先我们需要创建一个能跟着鼠标移动的自定义光标元素:
HTML 结构
在页面里添加一个专属的光标容器:
<div class="custom-cursor"></div>
CSS 样式
隐藏原生光标,给自定义光标设置基础样式:
/* 隐藏原生光标 */ body { cursor: none; } /* 自定义光标基础样式 */ .custom-cursor { position: fixed; width: 32px; height: 32px; border-radius: 50%; background-color: rgba(0,0,0,0.8); pointer-events: none; /* 避免干扰页面元素的正常交互 */ z-index: 9999; transition: all 0.1s ease; } /* 悬停H1时的光标样式(预留显示序号的空间) */ .custom-cursor.hover-h1 { background-color: rgba(0,0,0,1); transform: scale(1.5); display: flex; align-items: center; justify-content: center; color: white; font-size: 14px; font-weight: 500; }
JS 实现鼠标跟随逻辑
写一段简单的JS让光标跟着鼠标移动:
const customCursor = document.querySelector('.custom-cursor'); document.addEventListener('mousemove', (e) => { // 减去自身一半宽高,让光标中心对准鼠标位置 customCursor.style.left = `${e.clientX - 16}px`; customCursor.style.top = `${e.clientY - 16}px`; });
2. 实时获取当前幻灯片的序号
接下来要解决的核心问题:怎么拿到当前显示的幻灯片序号。这里分两种情况处理:
情况1:手动实现的幻灯片
如果是自己写的幻灯片逻辑,假设你的结构是这样的:
<div class="slides"> <div class="slide active">...</div> <div class="slide">...</div> <div class="slide">...</div> </div>
可以写一个函数实时获取当前活跃的幻灯片索引:
function getCurrentSlideIndex() { const slides = document.querySelectorAll('.slide'); let currentNum = 1; // 序号从1开始计数 slides.forEach((slide, index) => { if (slide.classList.contains('active')) { currentNum = index + 1; } }); return currentNum; }
情况2:用第三方插件(比如Swiper)的幻灯片
如果是用Swiper这类插件,直接调用插件API就能拿到当前索引:
// 假设你已经初始化了Swiper实例 const swiper = new Swiper('.swiper-container', { // 你的配置参数 }); function getCurrentSlideIndex() { return swiper.activeIndex + 1; // 同样转成从1开始的序号 }
3. 悬停H1时显示幻灯片序号
最后把光标和幻灯片序号关联起来,监听H1的hover事件:
const h1Element = document.querySelector('h1'); // 鼠标进入H1时,切换光标样式并显示序号 h1Element.addEventListener('mouseenter', () => { customCursor.classList.add('hover-h1'); customCursor.textContent = getCurrentSlideIndex(); }); // 鼠标离开H1时,恢复光标默认状态 h1Element.addEventListener('mouseleave', () => { customCursor.classList.remove('hover-h1'); customCursor.textContent = ''; });
额外优化(贴近参考效果)
参考你提到的桌面端图片悬停效果,可以给图片hover也加个光标变化:
const slideImages = document.querySelectorAll('.slide img'); slideImages.forEach(img => { img.addEventListener('mouseenter', () => { customCursor.style.transform = 'scale(0.8)'; customCursor.style.backgroundColor = 'rgba(255,255,255,0.8)'; }); img.addEventListener('mouseleave', () => { customCursor.style.transform = 'scale(1)'; customCursor.style.backgroundColor = 'rgba(0,0,0,0.8)'; }); });
注意事项
- 一定要给自定义光标加
pointer-events: none,不然会挡住页面元素的点击、hover等交互 - 如果网站做了响应式,记得在移动端恢复原生光标:
@media (max-width: 768px) { body { cursor: default; } .custom-cursor { display: none; } }
- 测试幻灯片切换时,要确保
getCurrentSlideIndex能实时拿到最新的序号,比如在幻灯片切换的回调里重新更新光标内容
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

