我正在构建我自己的自定义模态/对话框,我想把它放在可视区域的中心。例如,如果网页非常大,并且查看器向下滚动很远,然后单击以打开我的自定义模态/对话框,它将打开,但用户必须滚动到顶部才能看到它。我希望 Modal 在可视区域的中心打开。有人可以告诉我如何计算可视区域的中心,以便在显示模态时它可以绝对定位在那里。
Twitter bootstrap 使用他们的 Modal 执行此操作,它向下滑动到可视区域的中心,我想对我的自定义小部件执行相同操作,
我正在构建我自己的自定义模态/对话框,我想把它放在可视区域的中心。例如,如果网页非常大,并且查看器向下滚动很远,然后单击以打开我的自定义模态/对话框,它将打开,但用户必须滚动到顶部才能看到它。我希望 Modal 在可视区域的中心打开。有人可以告诉我如何计算可视区域的中心,以便在显示模态时它可以绝对定位在那里。
Twitter bootstrap 使用他们的 Modal 执行此操作,它向下滑动到可视区域的中心,我想对我的自定义小部件执行相同操作,
例如我正在使用这样的东西:
$(function() {
/**
* Moves an element to the center of the current screen (considering scrolling)
*/
$.fn.center = function (position) {
for (var i = 0; i < this.size(); i++) {
var t = $(this[i]);
t.css("position", position || "absolute");
var extra_top = position != "fixed" ? $(window).scrollTop() : 0;
var extra_left = position != "fixed" ? $(window).scrollLeft() : 0;
t.css("top", Math.max(0, ($(window).height() - t.outerHeight()) / 2 + extra_top) + "px");
t.css("left", Math.max(0, ($(window).width() - t.outerWidth()) / 2 + extra_left) + "px");
}
return this;
}
...
});
用法:$("#modal").center();
最简单的方法是查看模态窗口的高度和宽度。然后,将位置设置为固定
top: 50%;
left: 50%;
margin-left: - "INSERT WIDTH DIVIDED BY 2"
margin-top: - "INSERT HEIGHT DIVIDED BY 2"
这将始终使模式在页面上居中。
.page{
position: absolute;
height:1000px;
width:1000px;
background-color: blue;
}
.modal{
width: 300px;
height:300px;
top:50%;
left:50%;
margin-left:-150px;
margin-top:-150px;
position: fixed;
background-color:red;
}
请参阅我附加的 jsfiddle。 http://jsfiddle.net/yxTSh/