【问题标题】:How can I detect whether the mouse is in a certain part of the screen?如何检测鼠标是否在屏幕的某个部分?
【发布时间】:2019-02-22 20:27:50
【问题描述】:

所以我试图根据指针的 Y 坐标更改变量的值,但我不知道该怎么做。我试过这个:

 var righttext = mousemove.clientY;
 switch(righttext){
     case //not sure what to put here
     }

但我不知道在箱子里放什么。我想做的是有这样的例子:case "top 20% of screen"。我如何确定屏幕的坐标是什么,然后弄清楚如何在 switch 语句中使用它?

我想要影响值的部分只是水平划分的屏幕的五分之一。

编辑:

所以我被链接到另一个帖子,并找到了与我正在寻找的内容类似的答案。我将代码更改为如下所示:

document.addEventListener('mousemove', _.throttle(mouseMoveEventAction, 200));

function mouseMoveEventAction(e) {
	changetext(isInsideThreshold(e.clientY));
}
var rpaneltext = "";

function changetext(isActive) {
  if (isActive) {
      rpaneltext = "awareness";
  } else {
      rpaneltext = "";
  }
}

function isInsideThreshold(cursorY) {
	var threshold = .2;
	var clientHeight = document.documentElement.clientHeight;
  return cursorY > (clientHeight - threshold);
}
但它仍然不起作用。有任何想法吗?

项目here:将受到righttext影响的部分是document.querySelector(".r2").textContent = righttext

【问题讨论】:

  • 当你说前 20% 时,你是指整个屏幕,包括它是否可滚动,还是只是直接的视口?
  • switch 不适合这个任务,case 会和给定的值做严格的相等比较,不能逐个像素遍历整个屏幕。
  • @zfrisch 这将是一个不可滚动的目录页面,所以只是直接的视口。
  • 不同的部分需要不同的方法。我们在谈论哪些部分(形状、价值等)?定义一些,人们会提出一些解决方案。然后,您可以将解决方案应用于您的特定需求。

标签: javascript html variables pts


【解决方案1】:

您可以查看window.innerHeightwindow.innerWidth。它们返回视口尺寸。

如果使用这样的 if-else 逻辑,您可能会有更好的运气。

if (event.clientY < window.innerHeight / 2) {
    // it's in the upper half
} else {
    // it's in the lower half
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2023-03-31
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    相关资源
    最近更新 更多