繁体   English   中英

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

[英]Position DIV at cursor but within viewable area

我正在使用下面的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保持在可视区域内。

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

我们还添加了向左滚动和滚动顶部值,因此我们的计算不会错误地认为它是可见的; 如果你的情况不需要,你可以删除它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM