我试图在鼠标光标下方显示一个 popup-div,但它应该完全在可见区域内。显示鼠标光标下方的 div:
var popupHeight = $("#popup").height();
var popupWidth = $("#popup").width();
$("#popup").css({
"position" : "absolute",
"top" : lastClickPosition.pageY - (popupHeight/2),
"left" : lastClickPosition.pageX - (popupWidth/2))
});
这种简单方法的问题在于,popup-div 可能部分位于屏幕之外。所以我试图计算它留在屏幕内的最小和最大偏移量:
Math.min(Math.max(0, lastClickPosition.pageY - (popupHeight/2)),
windowHeight - popupHeight - 20)+"px"
但是这种方法在页面向下滚动后失败了,因为pageX/Y是相对于页面而不是可见部分。
还有其他想法吗?
最佳答案
您需要在窗口
的scrollTop
中添加。参见 scrollTop
$(window).scrollTop(); // this is the scroll distance from the top
The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.
关于javascript - 如何将鼠标光标下方的 popup-div 居中但将其完全保留在窗口内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4411247/