自定义光标页面加载时初始位置异常的解决方法求助
自定义光标初始定位问题
我的自定义光标功能正常,但页面加载时会显示在页面左上角,直到用户移动鼠标才会跳转到实际光标位置,怎么让它初始就定位在真实光标所在处?
问题原因
绑定DOMContentLoaded事件触发cursor函数时,事件对象并非鼠标移动事件,导致e.pageY和e.pageX为undefined,自定义光标因无效的定位值回到绝对定位默认的左上角位置。
解决方案
方案1:移除无效绑定+初始隐藏光标
- 移除
window.addEventListener('DOMContentLoaded', cursor);,该事件无法提供鼠标位置数据,属于无效绑定。 - 初始给自定义光标设置
opacity: 0隐藏,第一次鼠标移动时再显示并设置正确位置。
修改后的完整代码如下:
JavaScript
let mouseCursor = document.querySelector(".cursor"); let Links = document.querySelectorAll("a"); let iframes = document.querySelectorAll("iframe"); let logo = document.querySelector(".logo-error"); // 初始隐藏光标 mouseCursor.style.opacity = "0"; window.addEventListener('mousemove', cursor); function cursor(e){ // 第一次移动时显示光标 mouseCursor.style.opacity = "1"; mouseCursor.style.top = `calc(${e.pageY}px - 1rem)`; mouseCursor.style.left = `calc(${e.pageX}px - 1rem)`; } Links.forEach(link =>{ if ( link !== logo ){ link.addEventListener("mouseleave", () => { mouseCursor.classList.remove("link-grow"); }); link.addEventListener("mouseover", () => { mouseCursor.classList.add("link-grow"); }); } }); iframes.forEach(frame =>{ frame.addEventListener("mouseleave", () => { mouseCursor.classList.remove("hide"); }); frame.addEventListener("mouseover", () => { mouseCursor.classList.add("hide"); }); });
CSS
body{ cursor: none; } .main{ width: 100%; height: 100vh; background-color: black; display: flex; flex-direction: column; justify-content: center; align-items: center; } a{ font-size: 40px; color: white; } .cursor{ width: 2rem; height: 2rem; border: 2px solid white; border-radius: 50%; position: absolute; transition: all 0.3s ease; transition-property: background, transform, opacity; /* 添加透明度过渡 */ transform-origin: center center; z-index: 20000; pointer-events: none; opacity: 0; /* 初始隐藏 */ } .link-grow{ transform: scale(1.2); background: white; mix-blend-mode: difference; } a:-webkit-any-link { cursor: none; } .logo-error:hover .cursor{ display: none !important; } .hide { display: none !important; }
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="cursor"></div> <div class="main"> </div>
方案2:固定初始位置(可选)
如果希望页面加载时,即使用户未移动鼠标,光标也显示在页面中心,可在DOMContentLoaded时手动设置中心定位:
window.addEventListener('DOMContentLoaded', () => { const centerX = window.innerWidth / 2; const centerY = window.innerHeight / 2; mouseCursor.style.top = `calc(${centerY}px - 1rem)`; mouseCursor.style.left = `calc(${centerX}px - 1rem)`; }); window.addEventListener('mousemove', cursor);
内容的提问来源于stack exchange,提问作者gjjr
相关产品推荐
相关产品推荐

