首页 > 解决方案 > Center Custom Cursor

问题描述

I created a custom cursor that follows the mouse. I would like to have the custom circle grow larger when hovered over links. The problem that I am having is that when the circle animates to a larger circle, it no longer is centered to the cursor. I'm not too sure how to keep the custom circle centered as it grows in size. The code below is the JS used to have the custom circle follow the cursor. Thank you in advance!

let clientX = -100;
let clientY = -100;
const innerCursor = document.querySelector(".cursor--small");

const initCursor = () => {

  document.addEventListener("mousemove", e => {
    clientX = e.clientX;
    clientY = e.clientY;
  });
  

  const render = () => {
    innerCursor.style.transform = `translate(${clientX}px, ${clientY}px)`;

    requestAnimationFrame(render);
  };

  requestAnimationFrame(render);
};

initCursor();

标签: javascriptcursor

解决方案


无法以编程方式移动用户的光标。您可以将其锁定在某个位置,但这会产生糟糕的用户体验,并且可能在其他方面存在问题(跨浏览器问题)。

https://stackoverflow.com/a/19870963/1772933

我建议使用样式为悬停创建更大的“命中”区域。

a.cursor-thing{
display:inline-block;
padding:20px;
margin:-20px;
}

a.cursor-thing:hover{
background:#f00;
}
Here is a sentence where you can <a href='#' class='cursor-thing'>hover over me</a> or even  <a href='#' class='cursor-thing'>hover over me</a>.


推荐阅读