我有一个 jquery 弹出脚本,为了使弹出窗口在屏幕上居中,代码如下:
function centerPopup(){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(".popupContent").height();
var popupWidth = $(".popupContent").width();
$(".popupContent").css({
"position": "fixed",
"top": windowHeight/2-popupHeight/2,
"left": windowWidth/2-popupWidth/2
});
}
这有效,除非我需要激活 div 标签内的弹出窗口。它看起来更靠下,有时甚至脱离了页面。我假设它认为 div 标签的顶部是页面顶部。
我怎样才能解决这个问题并让它找到实际的主页顶部?
最佳答案
您可以尝试将此元素在浏览器中居中
$.fn.center = function () {
this.css("position","absolute");
this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
$(".popupContent").center();
这是一个example .
更新: example .
关于jquery弹出窗口找到真正的顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9838939/