将DIV放置在光标处,但在可视区域内

Position DIV at cursor but within viewable area

本文关键字:可视 区域 光标 DIV      更新时间:2023-09-26

我使用下面的showDiv函数在光标位置显示div弹出式菜单,但我不知道如何调整它,使菜单不会从可见区域的底部或右侧边缘消失,是否有可能在显示div之前对此进行补偿?

var posx;
var posy; 
function getMouse(e){ 
 posx = 0;
 posy = 0; 
 if (!e) var e = window.event; 
 if (e.pageX || e.pageY){ 
  posx = e.pageX;
  posy = e.pageY; 
 } 
 else if (e.clientX || e.clientY){ 
  posx = e.clientX;
  posy = e.clientY; 
 } 
} 
function showDiv(id){ 
 var obj = document.getElementById(id); 
 obj.style.left=posx+'px'; 
 obj.style.top=posy+'px'; 
 obj.style.display='block';
}
...
<body onMouseMove="getMouse(event)">

function showDiv(id){ 
  var obj = document.getElementById(id),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0) - (obj.clientWidth || obj.offsetWidth),
    screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0) - (obj.clientHeight || obj.offsetHeight);
  obj.style.left = Math.min(posx, screenWidth) + 'px'; 
  obj.style.top = Math.min(posy, screenHeight) + 'px'; 
  obj.style.display = 'block';
}

这将使div保持在可视区域内。

你只需检查宽度加上位置等是否大于或小于可视区域的值。

我们还添加了scroll left和scroll top的值,这样我们的计算就不会错误地认为它是可见的;如果在你的情况下不需要,你可以删除它。

function showDiv(id, posX, posY) {
  var obj = document.getElementById(id),
      objWidth = obj.offsetWidth,
      objHeight = obj.offsetHeight,
      docX = window.pageXOffset || document.documentElement.scrollLeft,
      docY = window.pageYOffset || document.documentElement.scrollTop,
      winWidth = document.documentElement.clientWidth,
      winHeight = document.documentElement.clientHeight;
  posX += docX;
  posY += docY;
  if (posX < docX) {
    posX = docX;
  } else if (posX + objWidth > winWidth + docX) {
    posX = docX + (winWidth - objWidth);
  }
  if (posY < docY) {
    posY = docY;
  } else if (posY + objHeight > winHeight + docY) {
    posY = docY + (winHeight - objHeight);
  }
  obj.style.top = posY + 'px';
  obj.style.left = posX + 'px';
  obj.style.display = 'block';
}