2010-07-08 59 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去後面....