如何在文本上移动自定义光标

问题描述

我制作了一个自定义光标,但它在文本(p、h1、按钮、跨度)上无法正常工作。这是代码

html:

<!-- custom cursor -->
<div class="cursor"></div>

js:

    const cursor = document.querySelector(".cursor");

    document.addEventListener("mouSEOver",(e) => {
        cursor.style.left = e.pageX + "px";
        cursor.style.top = e.pageY  + "px";
        console.log(e.pageX,e.pageY); // i checked pageX and pageY values also not change when cursor moves over a text or button

     })

CSS:

.cursor{
    position: fixed;
    width: 13px;
    height: 13px;
    border-radius: 50%;
    background-color: #ffffff38;
    transition-duration: 0.16s;
    -o-transition-duration: 0.16s;
    -moz-transition-duration: 0.16s;
    -webkit-transition-duration: 0.16s;
    transition-timing-function:ease;
    -o-transition-timing-function:ease;
    -moz-transition-timing-function:ease;
    -webkit-transition-timing-function:ease;
    transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -webkit-transform: translate(-50%,-50%);
    pointer-events: none;
    mix-blend-mode: difference;
    /* display: none; */
    z-index: 10000;
}
    

它在链接上运行良好。你能告诉我如何让光标平滑移动(在所有文本和按钮上)

解决方法

当您将鼠标移到某个元素上时会触发 mouseover 事件 - 但当您在该元素内移动鼠标时它不会一直触发。

您是否尝试过 mousemove

,

我认为下面的代码会对你有所帮助。您的代码中有一些错误,例如光标 background-color: #ffffff38; 的背景颜色,这是白色的,在白页中看不到。而且我隐藏了原始光标。 在 JavaScript 代码中,您使用了 mouseover,每次鼠标进入特定区域时都会触发,您应该使用 mousemove,每次移动鼠标时都会触发。

const cursor = document.querySelector(".cursor");

document.addEventListener("mousemove",(e) => {
  cursor.style.left = e.pageX + "px";
  cursor.style.top = e.pageY + "px";
  console.log(e.pageX,e.pageY);
  // i checked pageX and pageY values also not change when cursor moves over a text or button

})
html{
  cursor: none;
}
.cursor {
  position: absolute;
  width: 13px;
  height: 13px;
  border-radius: 50%;
  border: 1px solid black;
  z-index: 10000;
}
<!-- custom cursor -->
<div class="cursor"></div>