javascript - 如何将鼠标光标下方的 popup-div 居中但将其完全保留在窗口内?

标签 javascript jquery

我试图在鼠标光标下方显示一个 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/

相关文章:

javascript - Uncaught ReferenceError : $stateProvider is not defined Angular UI Router

javascript - 当用户试图离开页面时,如何执行 javascript 函数?

javascript - 用文本替换整数

javascript - GeoIP2 指定要查询的IP

javascript - 是否有 Jquery 或 Dojo 或纯 JavaScript 方式将 div 转换为图像?

javascript - 尝试使用 jQuery.data() API 在 jQuery 插件中缓存函数

jquery - IE7 jquery .each 数组

javascript - 使用 jquery 和推送状态从 url 中删除 url 参数

javascript - 如何通过单击按钮获取单元格值

javascript - Symfony 4 带有 jquery 插件和 WebEncore