Why can't I reliably capture a mouseout event?

后端 未结 6 1126
日久生厌
日久生厌 2020-11-30 00:18

I need to know when the mouse cursor leaves a div. So I hook up the mouseout event. However, if I move the mouse very quickly out of the div<

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 01:04

    Here's a simple workaround.

    In your onMouseOver listener, you can add a 'mousemove' listener to the window:

    { setMouseOver(true) let checkMouseLeave = (e: MouseEvent) => { if (rootRef.current && !rootRef.current.contains(e.target as HTMLElement)) { setMouseOver(false) window.removeEventListener('mousemove', checkMouseLeave) } } window.addEventListener('mousemove', checkMouseLeave) } >

    Then you can check on each mouse move until the mouse is outside of your div (rootRef.current in our example).

提交回复
热议问题