你其實不需要使用JavaScript來實現這一點。它可以用純CSS完成。
如果你仍然想使用JS,你基本上只需要得到window.innerWidth
和window.innerHeight
並將它們除以2.這將在窗口的中心給你一個點。然後只需從您的元素和高度的一半中減去寬度的一半即可抵消要居中元素的left
和top
位置。這是必要的,因爲定位是相對於文檔的左上角。
當您使用絕對定位元素的CSS解決方案確保父元素位置設置爲相對。
這是一個以JS和CSS爲中心的例子。
var centerDiv = document.querySelector('.center-js'),
showHideBtn = document.querySelector('.show-hide'),
winW = 0,
winH = 0;
// this is just the button click handler.
showHideBtn.addEventListener('click', function() {
if (centerDiv.style.opacity != 0) {
centerDiv.style.opacity = 0;
this.textContent = "Hide CSS centering";
} else {
centerDiv.style.opacity = 1;
this.textContent = "Show CSS centering";
}
}, false);
// here is the win resize handler;
function windowResize() {
winW = window.innerWidth;
winH = window.innerHeight;
centerDiv.style.top = (winH/2) - (centerDiv.clientHeight/2) + 'px';
centerDiv.style.left = (winW/2) - (centerDiv.clientWidth/2) + 'px';
}
window.addEventListener("resize", windowResize, false);
windowResize();
centerDiv.style.opacity = 1;
html {
position: relative;
min-height: 100%;
font-family: sans-serif;
color: white;
}
div {
text-align: center;
line-height: 200px;
vertical-align: middle;
}
.center-js {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
background: black;
opacity: 1;
transition: opacity .5s linear 0s;
z-index: 1020;
}
.center-css {
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
width: 200px;
height: 200px;
background: red;
z-index: 1010;
}
<button class="show-hide">Show CSS centering</button>
<div class="center-js">JS centering</div>
<div class="center-css">CSS centering</div>
歡迎的話,請花一點時間閱讀本[如何對提問](http://stackoverflow.com/help/how-to-ask)指南 – gmo
你應該使用CSS進行定位,請參閱http://css-tricks.com/centering-in-the-unknown/ – DonutReply