0

我制作了一个自定义光标,但它在文本(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;
}
    

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

4

2 回答 2

1

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

你试过mousemove吗?

于 2021-07-17T19:37:36.363 回答
0

我认为下面的代码会对您有所帮助。您的代码中有一些错误,例如光标的背景颜色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>

于 2021-07-17T20:01:44.750 回答