2011-09-11 56 views

回答

4

我認爲沒有js需要。 CSS將做到這一點(see here):

body { 
    background: #888; 
} 

.box { 
    width: 100px; 
    height: 100px; 
    background: #ccc; 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    margin: -50px 0 0 -50px; 
} 

UPD

如果您沒有固定的元素的寬度/高度:

JS(元素打開時):

element.style.margitLeft = -element.offsetWidth/2 
element.style.margitTop = -element.offsetHeight/2 

CSS:

.box { 
    background: #ccc; 
    position: fixed; 
    left: 50%; 
    top: 50%; 
} 
+0

只有當盒子的寬度*和高度已知 – Hristo

+0

+1這是超級酷。但是,我希望元素保留在打開的位置,這就是爲什麼需要javascript。 – 7elephant

+0

「停留在哪裏」是什麼意思?或者就此而言「打開」? – Quentin