How can I detect when the mouse leaves the window?

2019-01-01 15:27发布

I want to be able to detect when the mouse leaves the window so I can stop events from firing while the user's mouse is elsewhere.

Any ideas of how to do this?

16条回答
怪性笑人.
2楼-- · 2019-01-01 15:41

In order to detect mouseleave without taking in account the scroll bar and the autcomplete field or inspect :

document.addEventListener("mouseleave", function(event){

  if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
  {

     console.log("I'm out");

  }
});

Conditions explanations:

event.clientY <= 0  is when the mouse leave from the top
event.clientX <= 0  is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom
查看更多
闭嘴吧你
3楼-- · 2019-01-01 15:44

Using the onMouseLeave event prevents bubbling and allows you to easily detect when the mouse leaves the browser window.

<html onmouseleave="alert('You left!')"></html>

http://www.w3schools.com/jsref/event_onmouseleave.asp

查看更多
孤独总比滥情好
4楼-- · 2019-01-01 15:48

I take back what i said. It is possible. I wrote this code, works perfectly.

window.onload = function() {

    $span = document.getElementById('text');

    window.onmouseout = function() {
        $span.innerHTML = "mouse out";  
    }

    window.onmousemove = function() {
        $span.innerHTML = "mouse in";   
    }

}

works in chrome, firefox, opera. Aint tested in IE but assume it works.

edit. IE as always causes trouble. To make it work in IE, replace the events from window to document:

window.onload = function() {

    $span = document.getElementById('text');

    document.onmousemove = function() {
        $span.innerHTML = "mouse move";
    }

    document.onmouseout = function() {
        $span.innerHTML = "mouse out";
    }

}

combine them for crossbrowser kick ass cursor detection o0 :P

查看更多
看风景的人
5楼-- · 2019-01-01 15:50
$(window).mouseleave(function() {
 alert('mouse leave');
});
查看更多
旧人旧事旧时光
6楼-- · 2019-01-01 15:53

If you are using jQuery then how about this short and sweet code -

$(document).mouseleave(function () {
    console.log('out');
});

This event will trigger whenever the mouse is not in your page as you want. Just change the function to do whatever you want.

And you could also use:

$(document).mouseenter(function () {
    console.log('in');
});

To trigger when the mouse enters back to the page again.

Source: https://stackoverflow.com/a/16029966/895724

查看更多
时光乱了年华
7楼-- · 2019-01-01 15:53

I haven't tested this, but my instinct would be to do an OnMouseOut function call on the body tag.

查看更多
登录 后发表回答