You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅在鼠标悬停指定元素时更改自定义光标样式?

解决自定义光标悬停后无法恢复样式的问题

你的问题出在只处理了鼠标悬停元素的事件,没有添加鼠标移出元素的逻辑,导致光标样式无法复原。下面用原生JS提供两种可行方案:

方案1:补充内联事件(基于你原有的写法)

修改HTML,给control元素添加onmouseout事件,调用恢复光标样式的函数:

<div id="cursor"></div>
<div id="control" onmouseover="cursorFill()" onmouseout="cursorReset()"></div>

在JS中添加恢复函数:

const cursor = document.querySelector('#cursor');
document.addEventListener('mousemove', (e) => {
  cursor.style.left = e.pageX + 'px';
  cursor.style.top = e.pageY + 'px';
})

function cursorFill() {
  cursor.style.backgroundColor = "#fff";
}

function cursorReset() {
  cursor.style.backgroundColor = "transparent";
}

方案2:使用事件监听(更推荐的写法,分离HTML和JS逻辑)

这种方式不需要在HTML中写内联事件,代码更易维护:

HTML

<div id="cursor"></div>
<div id="control"></div>

JS

const cursor = document.querySelector('#cursor');
const controlEl = document.querySelector('#control');

// 光标跟随逻辑
document.addEventListener('mousemove', (e) => {
  cursor.style.left = e.pageX + 'px';
  cursor.style.top = e.pageY + 'px';
})

// 绑定悬停和移出事件
controlEl.addEventListener('mouseenter', () => {
  cursor.style.backgroundColor = "#fff";
});

controlEl.addEventListener('mouseleave', () => {
  cursor.style.backgroundColor = "transparent";
});

CSS部分保持你原有的代码即可:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  cursor: none;
}

body {
  background-color: #000;
  align-items: center;
  justify-content: center;
  display: flex;
}

#cursor {
  position: fixed;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 5px solid #fff;
  background-color: transparent;
  transform: translate(-50%, -50%);
  pointer-events: none;
  mix-blend-mode: difference;
}

#control {
  background-color: #fff;
  width: 10em;
  height: 10em;
  margin-top: 50vh;
}

两种方案都能实现:鼠标悬停control元素时光标变为白色填充,移出后恢复透明边框样式。

内容的提问来源于stack exchange,提问作者SHRUBBY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 10:16:03