2015-07-28 81 views
0

我怎樣才能更正我的代碼,以保持在窗口的中心股利,以保持DIV的中心在調整大小時:調整窗口使用JavaScript

window.addEventListener("resize",handleResize,false); 
 
\t function handleResize(){ 
 
\t \t var newwidth = window.innerWidth.value; 
 
\t \t var newheight = window.innerHeight.value; 
 
\t \t window.resizeTo(newwidth , newheight); 
 
\t }

+1

歡迎的話,請花一點時間閱讀本[如何對提問](http://stackoverflow.com/help/how-to-ask)指南 – gmo

+1

你應該使用CSS進行定位,請參閱http://css-tricks.com/centering-in-the-unknown/ – DonutReply

回答

0

你其實不需要使用JavaScript來實現這一點。它可以用純CSS完成。

如果你仍然想使用JS,你基本上只需要得到window.innerWidthwindow.innerHeight並將它們除以2.這將在窗口的中心給你一個點。然後只需從您的元素和高度的一半中減去寬度的一半即可抵消要居中元素的lefttop位置。這是必要的,因爲定位是相對於文檔的左上角。

當您使用絕對定位元素的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>