检查哪一边在鼠标指针周围有更多的空间

Check which side has more space around mouse pointer

本文关键字:空间 周围 鼠标指针 检查      更新时间:2023-09-26

我正在构建一个自定义工具提示功能,我应该在图像上显示视频作为工具提示。现在,我有一些初始的东西工作,但是我在寻找鼠标指针周围应该显示工具提示的区域时卡住了。

我让工具提示总是在鼠标光标的右下角可见,无论鼠标当前在屏幕的哪个位置,这就是我目前所做的:

window.onmousemove = function (e) {
    var x = e.clientX, y = e.clientY;
    tooltipSpan.style.top = (y + 10) + 'px';
    tooltipSpan.style.left = (x + 10) + 'px';
};

其中tooltip是我的目标元素。我正在寻找的是,我的代码应该找到屏幕上可用鼠标周围的最大区域,并调整工具提示以显示在那里。这方面的任何提示都将大有帮助。

注意:jQuery不是一个选项,我必须建立在核心JS

  1. 你可以得到的宽度和尺寸的视口使用window.innerWidthwindow.innerHeight(在我的例子下面this指的是window,因为代码在window内运行)
  2. 使用视口尺寸和使用ev.clientX/Y的鼠标位置,您可以确定光标左/右和上/下侧的像素空间,如下例所示。

  3. 使用offsetWidthoffsetHeight属性,我们得到工具提示的尺寸,我们可以使用它来设置工具提示相对于光标位置的位置。例如,如果topleleft象限是最大的,则工具提示将显示相对于光标的左上角(意味着工具提示的右下角将"触摸"光标)。

我希望这个例子对你有帮助:).

 var tooltip = this.document.getElementsByClassName("tooltip")[0];
window.onmousemove = function(ev) {
  // Getting pixel space 
  var leftPixelSpace = ev.clientX;
  var rightPixelSpace = this.innerWidth - leftPixelSpace; 
  var topPixelSpace = ev.clientY;
  var bottomPixelSpace = this.innerHeight - topPixelSpace;
  // Determining the position of topleft corner of the tooltip
  var tooltipPosX = leftPixelSpace > rightPixelSpace ? leftPixelSpace  - tooltip.offsetWidth : leftPixelSpace;
  var tooltipPosY = topPixelSpace > bottomPixelSpace ? topPixelSpace - tooltip.offsetHeight : topPixelSpace;
  
  // Setting tooltip position 
  tooltip.style.left = tooltipPosX+"px";
  tooltip.style.top = tooltipPosY+"px";
};
.tooltip {
  width: 150px;
  height: 100px;
  border: 1px solid black;
  background-color : lightblue;
  text-align: center;
  position: absolute
}
<div class="tooltip">floating tooltip</div>

像这样?switch,包含计算鼠标光标所在象限的条件。

var wM = window.innerWidth / 2;
var hM = window.innerHeight / 2;
document.addEventListener('mousemove', function(e) {
    var w = e.clientX;
    var h = e.clientY;
    var pos;
    switch (true) {
        case (w <= wM && h <= hM):
            pos = 'top-left';
            break;
        case (w <= wM && h >= hM):
            pos = 'bottom-left';
            break;
        case (w > wM && h < hM):
            pos = 'top-right';
            break;
        case (w > wM && h > hM):
            pos = 'bottom-right';
            break;
	default:
            pos = undefined;//Here you could even assign a default quadrant to relay on, in case any condition is met.
    }
    console.log(pos);
});

  • wM for widthMiddle,窗口宽度的中点。
  • hM:相同,但高度不同。
  • w表示鼠标宽度/X位置;h for height/y
  • 根据象限系统的条件的开关。