【发布时间】:2010-07-08 10:16:47
【问题描述】:
如何使用 javascript 将弹出分区与显示器/屏幕中心对齐?
我尝试使用 screen.width 和 screen.height 来获得中心。但是该分区与垂直滚动页面的中心对齐
提前感谢您的任何帮助和建议
【问题讨论】:
标签: javascript
如何使用 javascript 将弹出分区与显示器/屏幕中心对齐?
我尝试使用 screen.width 和 screen.height 来获得中心。但是该分区与垂直滚动页面的中心对齐
提前感谢您的任何帮助和建议
【问题讨论】:
标签: javascript
试试这个:
<div id="popup" class="popup">
This a vertically and horizontally centered popup.
</div>
<a onclick="showPopup('popup');">Show Popup</a>
<style type="text/css">
.popup {
width:200px;
height:100px;
position:absolute;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
display:none;
}
</style>
<script type="text/javascript">
function showPopup(id) {
var popup = document.getElementById(id);
popup.style.display = 'block';
}
</script>
CSS 解释: div 是 200x100,您将其放置在距顶部 50% 和距左侧 50% 的位置,但要使其完全居中,您需要从 50% 的值中减去宽度和高度的一半,这样做的方法是使用负边距,因此 margin-top 应该是 height/2 的负值,margin-left 应该是 width/2 的负值。
【讨论】:
只使用 CSS 怎么样:
<div class="div">Some Content......</div>
.div {
margin-left: auto;
margin-right: auto;
}
【讨论】:
尝试:
function msgBox(message)
{
var msgbox = document.getElementById("msgbox");
msgbox.innerHTML = message;
var x = (window.innerWidth / 2) - (msgbox.offsetWidth / 2);
var y = (window.offsetHeight / 2) - (msgbox.offsetHeight / 2);
msgbox.style.top = y;
msgbox.style.left = x;
msgbox.style.display = "block";
}
【讨论】:
尝试固定定位:
#box {
position: fixed;
width: 40%;
margin: 200px 30%;
}
它只是水平居中。垂直将需要一些玩。我不知道浏览器在垂直对齐方面的行为有何不同。
【讨论】:
我在任何需要滚动的网页上也遇到过垂直居中问题。
切换到位置:固定解决了它,所以:
position:fixed;
top:50%;
left:50%;
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */
这适用于 firefox、google chrome、safari (pc) 和 IE9。
不幸的是,我希望它出现在 pdf file 前面 - 使用 Firefox、Chrome 时弹出窗口确实出现在前面,但在 IE9 和 Safari 中却落后了......
【讨论】: