简体   繁体   中英

Position DIV at cursor but within viewable area

I'm using the showDiv function below to display a DIV popup menu at the cursor position but I can't figure out how to tweak it so that the menu doesn't disappear off the bottom or right-hand edge of the viewable area, is it possible to compensate for this before displaying the 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'; } 

This should keep the div within the view-able area.

You just check to see if the width plus the position etc are more or less than the values of the view-able area.

We also add on the scroll left and scroll top values so our calculations don't mistakenly think it's visible; you can remove that if it's not needed in your case though.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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