在悬停 Div 时跟随鼠标,但仅在 Div 上

Follow mouse on Hover of Div but only on Div

不知道该怎么做,但我已经通过 codepen 正确设置了第一部分 here 除非将鼠标悬停在黑色 div 上,否则不确定如何阻止它发生。基本上我希望有正常的鼠标功能,直到你悬停这个黑色 div 而不是触发 script/function。我也试图在不使用任何库和仅使用 JS 的情况下实现这一目标。

下面的代码

document.addEventListener("mousemove", function() {
  myFunction(event);
});

var mouse;
var cursor = document.getElementById("cursor");

function myFunction(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  cursor.style.left = (mouseX - 55) + "px";
  cursor.style.top = (mouseY - 55) + "px";


}
body {
  background: #FFFDFA;
}

#cursor {
  height: 100px;
  width: 100px;
  position: absolute;
  backface-visibility: hidden;
  z-index: 9999999;
  cursor: none;
}

div {
  background: black;
  width: 200px;
  height: 100px;
  margin: 30px;
  cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor"></img>

<div>
</div>

您只需将事件侦听器添加到 div 元素即可。您还需要在光标元素上禁用 pointerEvents,这样鼠标就不会注册为在光标之上,而不是 div.

document.getElementById("div").addEventListener("mousemove", function() {
  myFunction(event);
});

var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  cursor.style.left = (mouseX - 55) + "px";
  cursor.style.top = (mouseY - 55) + "px";


}
body {
  background: #FFFDFA;
}

#cursor {
  height: 100px;
  width: 100px;
  position: absolute;
  backface-visibility: hidden;
  z-index: 9999999;
  pointer-events: none; /* pointer-events: none is needed */
  cursor: none;
}

div {
  background: black;
  width: 200px;
  height: 100px;
  margin: 30px;
  cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor"></img>

<div id="div"></div> <!--add id-->

编辑:如果您希望鼠标移出时光标消失:

document.getElementById("div").addEventListener("mousemove", function() {
  myFunction(event);
});

var mouse;
var cursor = document.getElementById("cursor");
function myFunction(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  cursor.style.left = (mouseX - 55) + "px";
  cursor.style.top = (mouseY - 55) + "px";
}
body {
  background: #FFFDFA;
}

#cursor {
  height: 100px;
  width: 100px;
  position: absolute;
  backface-visibility: hidden;
  z-index: 9999999;
  pointer-events: none; /* pointer-events: none is needed */
  cursor: none;
}

div {
  background: black;
  width: 200px;
  height: 100px;
  margin: 30px;
  cursor: none;
}
<img src="https://www.figurefoundry.xyz/metal-cursor.svg" id="cursor" hidden></img>

<div id="div" onmouseenter="cursor.hidden = false" onmouseleave="cursor.hidden=true"></div> <!--make cursor invisible on leave and visible on enter-->