Mouseleave triggered by click

前端 未结 6 1551
囚心锁ツ
囚心锁ツ 2021-01-01 11:38

I have an absolutely-positioned div, and I\'m trying to keep track of when the mouse moves over it, and when the mouse leaves. Unfortunately clicking on the text in the box

6条回答
  •  再見小時候
    2021-01-01 11:57

    The answer by @trincot almost worked for me. In my case I'm dealing with popovers. When I click on a button, it triggers a popover showing up on top of the triggering button. So document.elementFromPoint(e.clientX, e.clientY) returns the popover element rather than the triggering button. Here's how I solved this:

    mouseleave(ev: MouseEvent) {
        const trigger: HTMLElement = document.getElementById('#myTrigger');
        const triggerRect = trigger.getBoundingClientRect();
        const falsePositive = isWithingARect(ev.clientX, ev.clientY, triggerRect);
    
        if (!falsePositive) {
            // do what needs to be done
        }
    }
    
    function isWithingARect(x: number, y: number, rect: ClientRect) {
      const xIsWithin = x > rect.left && x < rect.right;
      const yIsWithin = y > rect.top && y < rect.bottom;
      return xIsWithin && yIsWithin;
    }
    

提交回复
热议问题