将DIV定位在光标处但仍在可视区域内

3
我正在使用以下的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)">

函数showDiv是否正在从getMouse函数中访问作用域变量?或者它们是在更高的作用域中定义的? - A1rPun
你能添加一个可用的代码片段吗? - sergdenisov
2个回答

0

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 仍然出现在屏幕底部之外。这是因为网页也延伸到了屏幕底部吗? - Andy Groom

0

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

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

我们还添加了滚动左侧和滚动顶部的值,以便我们的计算不会错误地认为它是可见的;如果在您的情况下不需要,可以将其删除。

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';
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接