使用javascript调整窗口大小,使div保持在中心位置



如何修改代码以使div在调整大小时保持在窗口的中心位置:

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

绝对不需要javascript编码:例如,使用具有绝对或相对定位的父容器的自动页边距

您实际上不需要使用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>

最新更新