如何实现鼠标跟踪时图片不旋转仅保持定位(附代码)
解决方案:让瞳孔跟随鼠标平移且保持原有姿态
核心调整思路
你之前的代码是通过旋转整个眼睛容器实现跟随效果,现在要改成只移动瞳孔(.eye::before伪元素)的位置,全程不旋转任何元素,同时限制瞳孔在圆形眼睛范围内活动。
修改后的完整代码
HTML(无需改动)
<section class="contact"> <div class="box"> <div class="eye"></div> </div> </section>
CSS 调整
.contact { display: flex; margin: 0 auto; justify-content: center; align-items: center; z-index: 1; } .box { display: flex; margin: 0; top: 35px; right: 0; bottom: 0; left: 0; position: absolute; align-items: center; justify-content: center; } .box .eye { position: relative; width: 200px; height: 200px; display: block; background-color: pink; border-radius: 50%; z-index: -1; overflow: hidden; /* 防止瞳孔跑出眼睛范围 */ } .box .eye::before { content: ""; position: absolute; /* 改绝对定位,相对父元素.eye */ top: 50%; left: 50%; /* 用CSS变量接收JS计算的偏移量,保持图片不旋转 */ transform: translate(-50%, -50%) translate(var(--pupil-x, 0), var(--pupil-y, 0)); width: 70px; height: 70px; border-radius: 50%; background-image: url(https://cdn-icons-png.flaticon.com/512/179/179531.png); background-position: center; background-repeat: no-repeat; background-size: cover; box-sizing: border-box; }
JavaScript 重写
document.querySelector("body").addEventListener("mousemove", eyeball); function eyeball(event) { const eyes = document.querySelectorAll(".eye"); eyes.forEach(eye => { // 获取眼睛中心的坐标 const rect = eye.getBoundingClientRect(); const eyeCenterX = rect.left + rect.width / 2; const eyeCenterY = rect.top + rect.height / 2; // 计算鼠标相对眼睛中心的偏移量 const dx = event.clientX - eyeCenterX; const dy = event.clientY - eyeCenterY; // 计算偏移距离,限制瞳孔在眼睛内部移动 const distance = Math.sqrt(dx * dx + dy * dy); const maxMove = (rect.width / 2) - 35; // 眼睛半径减去瞳孔半径 // 超过最大距离时按比例缩小偏移,避免瞳孔跑出 let moveX = dx; let moveY = dy; if (distance > maxMove) { const ratio = maxMove / distance; moveX = dx * ratio; moveY = dy * ratio; } // 通过CSS变量传递偏移量给瞳孔 eye.style.setProperty("--pupil-x", `${moveX}px`); eye.style.setProperty("--pupil-y", `${moveY}px`); }); }
关键说明
- 全程仅平移瞳孔,不旋转任何元素,完全保持图片原有姿态
- 通过数学计算限制瞳孔活动范围,确保不会跑出圆形眼睛
- 用CSS变量传递偏移量,让JS和CSS交互更简洁
内容的提问来源于stack exchange,提问作者OFFSNAKE
相关产品推荐
相关产品推荐

