useMouse
作用
获取鼠标位置
原理
是通过监听
mousemove
方法,获取鼠标的位置。并通过getBoundingClientRect
获取到target
元素的问题,从而计算出鼠标相对于元素的位置。
源码
typescript
import useRafState from '../useRafState'
import useEventListener from '../useEventListener'
import type { BasicTarget } from '../utils/domTarget'
import { getTargetElement } from '../utils/domTarget'
export interface CursorState {
screenX: number
screenY: number
clientX: number
clientY: number
pageX: number
pageY: number
elementX: number
elementY: number
elementH: number
elementW: number
elementPosX: number
elementPosY: number
}
const initState: CursorState = {
screenX: NaN,
screenY: NaN,
clientX: NaN,
clientY: NaN,
pageX: NaN,
pageY: NaN,
elementX: NaN,
elementY: NaN,
elementH: NaN,
elementW: NaN,
elementPosX: NaN,
elementPosY: NaN,
}
export default (target?: BasicTarget) => {
const [state, setState] = useRafState(initState)
// 监听鼠标移动事件
useEventListener(
'mousemove',
(event: MouseEvent) => {
const { screenX, screenY, clientX, clientY, pageX, pageY } = event
const newState = {
screenX,
screenY,
clientX,
clientY,
pageX,
pageY,
elementX: NaN,
elementY: NaN,
elementH: NaN,
elementW: NaN,
elementPosX: NaN,
elementPosY: NaN,
}
// 获取目标元素
const targetElement = getTargetElement(target)
// 如果目标元素存在,则计算鼠标相对于元素的位置
if (targetElement) {
const { left, top, width, height } = targetElement.getBoundingClientRect()
newState.elementPosX = left + window.pageXOffset
newState.elementPosY = top + window.pageYOffset
newState.elementX = pageX - newState.elementPosX
newState.elementY = pageY - newState.elementPosY
newState.elementW = width
newState.elementH = height
}
setState(newState)
},
{
target: () => document,
},
)
return state
}