繁体   English   中英

使用JavaScript调整窗口大小以将div保持在中心

[英]to resize the window to keep the div in the center using javascript

调整大小后,如何纠正代码以使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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM