检测光标是否在 jquery 定义的区域中

Detect if cursor is in a defined area with jquery

我有一个动态设置的 0.6 * $(window).width();0.7 * $(window).height(); 不可见区域,以页面为中心(因此该区域位于 0.2 * $(window).width();0.15 * $(window).height(); (0,0)页角)。

我希望光标根据光标在区域内还是区域外触发不同的交互。

document.onmousemove = function(e){
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    var windowW = $(window).width();
    var windowH = $(window).height();

    if (0.2 * windowW <= cursorX <= 0.8 * windowW && 0.15 * windowH <= cursorY <= 0.85 * windowH) {
      console.log("the cursor is inside the bound, do something.");
    } else {
      console.log("the cursor is outside the boud. do something else.");
    }
  }

目前,无论我的鼠标走到哪里,它只记录光标在边界内。我认为 if 语句有问题。我该如何解决这个问题?

编辑: 请注意,我还有一个 canvas 用于在底部使用光标进行绘图,所以我无法添加 div在顶部使用 mouseenter()mouseleave()。有哪些替代方案?

那个不可见区域的元素是什么?

你可以在那个位置设置一个div,有一个透明的作为背景颜色然后使用mouseenter来检测鼠标何时刚刚进入那个div(即隐藏区域)

看看这个:https://api.jquery.com/mouseenter/

我之前的代码肯定有逻辑错误。以不同方式编写 if 语句已解决问题。

if (cursorX <= 0.2 * windowW || cursorX >= 0.8 * windowW || cursorY <= 0.15 * windowH || cursorY >= 0.85 * windowH) {
  console.log("out of bound!")
} else {
  console.log("inside the bound!");
}