【问题标题】:Detect when the mouse leaves the top of the viewport?检测鼠标何时离开视口顶部?
【发布时间】:2014-11-25 06:19:39
【问题描述】:

我想检测鼠标何时离开顶部的视口(可以说是向北)。我在网上搜索并想出了How can I detect when the mouse leaves the window?。是一个好的开始,但它也会检测鼠标何时离开其他方向。我怎么能只检测到顶部的出口?

谢谢!

【问题讨论】:

  • 在检测到鼠标离开窗口后,跟踪位置并在最后一个已知位置放置一个守卫。
  • 你到底是什么意思?请您再解释一下好吗?
  • 我自己想出来的,谢谢!
  • 如果您想要一个有用的答案,您需要告诉我们您使用的语言和平台。请使用该信息编辑问题的标签。谢谢。

标签: viewport mouseleave


【解决方案1】:

为了在不考虑滚动条和自动完成字段的情况下检测鼠标离开:

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");

  }
});

那么你只需要删除条件:

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

【讨论】:

    【解决方案2】:

    使用这个插件:https://github.com/carlsednaoui/ouibounce

    当鼠标移出顶部视口时会触发一个事件。

    【讨论】:

      猜你喜欢
      • 2015-09-03
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      相关资源
      最近更新 更多