跳到主要内容

局部自定义鼠标样式

如果你想在页面中局部实现自定义鼠标指针的样式,这个组件可以帮到你。另外你也可以根据组件代码,了解网页中实现自定义鼠标指针所涉及的知识和原理。

代码实现

import React, { useState, useEffect } from "react";
import styles from './style.module.scss';
import clsx from 'clsx';

// 参数 id 为 页面中某个元素的id
export default function FlareCursor(props) {
const [position, setPosition] = useState({ x: 0, y: 0 });

const [isPointer, setIsPointer] = useState(false);
const [isInner, setIsInner] = useState(false);

const handleMouseMove = (e) => {
const el = document.getElementById(props.id);
const scrollY = document.documentElement.scrollTop || document.body.scrollTop
let inner = false;
if (el) {
if (e.clientX > el.offsetLeft &&
e.clientX < el.offsetLeft + el.offsetWidth &&
e.clientY > el.offsetTop - scrollY &&
e.clientY < el.offsetTop + el.offsetHeight - scrollY) {
inner = true;
}
}
setIsInner(inner);
setPosition({ x: e.clientX, y: e.clientY });

const target = e.target;

inner && setIsPointer(
window.getComputedStyle(target).getPropertyValue("cursor") === "pointer"
);
};

useEffect(() => {
window.addEventListener("mousemove", handleMouseMove);
return () => {
window.removeEventListener("mousemove", handleMouseMove);
};
}, []);

const flareSize = isPointer ? 0 : 30;

const cursorStyle = isPointer ? { left: "-100px", top: "-100px" } : {};

return (
<>
{
isInner ?
<div
className={clsx(styles.flare, isPointer ? styles.pointer : '')}
style={{
...cursorStyle,
left: `${position.x}px`,
top: `${position.y}px`,
width: `${flareSize}px`,
height: `${flareSize}px`,
}}
></div> : ''
}
</>
)
}