2010-07-08 63 views
11

如何使用javascript将弹出窗口对齐到监视器/屏幕中心?如何使用Javascript中心对齐弹出div div

我试过使用screen.width和screen.height来获得中心。但这种分化被对齐,以滚动页面的中心提前垂直

感谢所有帮助和建议

+0

尝试此http://咕。 gl/ZE21u3 – 2014-10-13 06:20:52

回答

20

试试这个:

<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的负值。

0

尝试:

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"; 
} 
+0

嗨不要在中心..可能是一些国防部可能会帮助..但没有得到它 – Parag 2010-07-08 10:49:29

+0

上面的两行代码应该像下面: var x =(window.innerWidth/2) - (msgbox .offsetWidth/2)+“px”; var y =(window.offsetHeight/2) - (msgbox.offsetHeight/2)+“px”; 此处“px”像素丢失。 – 2015-05-02 19:14:02

2

如何只用CSS做:

<div class="div">Some Content......</div> 

.div { 
    margin-left: auto; 
    margin-right: auto; 
} 
+0

它的一个模式框有点div 和我已经使用screen.height和screen.width属性的JavaScript来获得框中心。 但是,该方框涉及到滚动页面的垂直中心而不是可见区域的中心 – Parag 2010-07-08 10:41:53

0

尝试固定定位:

#box { 
    position: fixed; 
    width: 40%; 
    margin: 200px 30%; 
} 

这只是水平居中。垂直将需要一些玩。我不知道浏览器如何与垂直对齐不同。

0

我在任何需要滚动的网页上都有这个垂直居中问题。

切换到的位置是:固定的解决了这个问题,所以:

position:fixed; 
top:50%; 
left:50%; 
margin:-50px 0 0 -100px; /* [-(height/2)px 0 0 -(width/2)px] */ 

这个工作在Firefox,谷歌Chrome,Safari浏览器(PC)和IE9。

不幸的是,我希望它出现在pdf file面前 - 弹出使用Firefox,Chrome未出现在前面,但在IE9和Safari去后面....