自定义跟随鼠标光标遮挡DOM元素,无法穿透点击问题求助
解决自定义光标遮挡元素点击的问题
嘿,我太懂你遇到的这个糟心问题了——自定义光标飘在页面最上层看着挺酷,结果下面的按钮啥的全点不了,调z-index也没法兼顾视觉和交互。其实这事儿有个简单的CSS属性就能搞定!
问题根源
你的.customCursor是个绝对定位且z-index拉满的div,它会实实在在地“挡”在所有元素上方。浏览器默认会把鼠标事件(点击、hover这些)优先发给最上层的元素,所以你的光标div先接住了点击,下面的按钮根本没机会响应,这就是为啥只有光标没覆盖时才能点。
核心解决方案:pointer-events: none
CSS里的pointer-events属性就是专门解决这种“视觉在上但交互穿透”的需求!把它设为none后,这个元素会完全忽略所有鼠标事件,点击、hover等操作会直接穿透到它下面的元素,同时视觉上它依然稳稳待在最上层,完美兼顾你的需求。
修改后的代码
只需要在你的.customCursor样式里加一行代码就行,下面是完整的修改版:
window.CustomCursor = new(function() { const self = this; const css = ` .customCursor { z-index: 999; width: 22px; height: 22px; border: 1.2px solid #2980b9; border-radius: 50%; position: absolute; transition-duration: 200ms; transition-timing-function: ease-out; pointer-events: none; /* 关键修复代码 */ } `; // 创建样式标签 const style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.querySelector('head').appendChild(style); // 创建光标元素 const cursor = document.createElement('div'); cursor.className = "customCursor"; document.querySelector('body').appendChild(cursor); // 鼠标移动逻辑 document.addEventListener("mousemove", e => { const {pageX, pageY} = e; cursor.setAttribute(`style`, `top: ${pageY - 11}px; left: ${pageX - 11}px;`); }); document.addEventListener("click", e => { // 之后要加光标点击动画的话,直接在这里写逻辑就行,不受pointer-events影响 }); });
body { background: #0f1215; }
<button onclick="alert('Hi')">Button</button>
额外小贴士
如果之后你想给自定义光标加点击动画(比如点击时缩小一下),完全不用发愁——因为你是把click事件绑定在document上的,不是光标div本身,所以依然能监听到点击动作,同时不影响下面元素的正常交互。
内容的提问来源于stack exchange,提问作者Mike Smith
相关产品推荐
相关产品推荐

