检查鼠标是否已离开窗口的特定部分

时间:2016-06-01 05:49:42

标签: javascript windows mouseevent document

是否可以知道鼠标是否已离开窗口的特定部分?值如下:

var cursorX;
var cursorY;
document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}
document.addEventListener('mouseout', function(e) {
    var dims = elem.getBoundingClientRect();
    var top = window.scrollY + dims.top;
    var left = dims.left;
    var width = dims.width;
    var bottom = dims.height;
    if (what condition should be here) {
        console.log('yes mouse has left that portion')
        document.getElementById('div-in-the-end-of-body').style .display = 'none';
    }
});

例如,控制台日志中的dims值为ClientRect {top: 155.375, right: 621, bottom: 540.375, left: 313, width: 308…}

以下是我想要实现的目标。

enter image description here

编辑:身体末端的div具有绝对位置并且悬停在图像上。如果我在那个div图像上盘旋,请考虑鼠标离开它并隐藏div。这就是我想这样做的原因。

编辑#2:这是解决方案

 elem.onmouseout=function(){
    var dims = this.getBoundingClientRect();
        var top = window.scrollY + dims.top;
        var left = dims.left;
        var width = dims.width;
        var bottom = dims.height;
     if(top > 10 || left > 10 || width > 10 || bottom > 10){
            document.getElementById('div-in-the-end-of-body').style .display = 'none';
     }
 }

3 个答案:

答案 0 :(得分:0)

查看mouseout事件。或者,只要您的鼠标进入特定区域,就可以capture mouse events

答案 1 :(得分:0)

您可以将事件侦听器绑定到"区域"你想检查一下。由于您的区域是javascript中的对象,因此内置了事件侦听器,或者您可以使用obj.call来调用不属于您创建的对象的函数。例如,



let rects[] // this is your list of regions

for (let rect of rects) {
  rect.onMouseMove((e) => {
    // do something when mouse cursor is moving
  })

  rect.onMouseEnter((e) => {
    // do somthing when mouse cursor enters the area
  })

  rect.onMouseLeave((e) => {
    // do something when mouse cursor exits the area
  })
}




答案 2 :(得分:0)

好的,我已经找到了解决方案。以下是可能需要的人的工作代码。

elem.onmouseout=function(){
    var dims = this.getBoundingClientRect();
        var top = window.scrollY + dims.top;
        var left = dims.left;
        var width = dims.width;
        var bottom = dims.height;

     if(top > 10 || left > 10 || width > 10 || bottom > 10){
            console.log('yay!! ship has left the dock')
     }
}