[英]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.