繁体   English   中英

offsetHeight 获取不正确的 div 元素高度

[英]offsetHeight Getting Incorrect Height of div Element

我试图通过将其 position 设置为绝对值,将其最高值设置为 50%,然后将上边距减去 div 高度的一半,使屏幕上的 div 居中。 我用的是offsetHeight,但是offsetHeight属性返回的高度好像小于div元素的实际高度。 (见下面的截图)

有解决办法吗? 有没有我可以做的替代方法?

提前致谢。

offsetHeight 返回的高度为 69 px,而不是实际高度 328.375px。

 // Custom title let customTitle = document.getElementById("title"); chrome.storage.sync.get("title", (result) => { customTitle.textContent = result.title; }); // Centering container let container = document.getElementById("container"); container.style.marginTop = -container.offsetHeight / 2 + "px"; window.onresize = container.style.marginTop = -container.offsetHeight / 2 + "px";
 pre { color: white; display: block; font-family: 'Mulish', sans-serif; font-weight: 800; font-size: 96px; margin-block-start: 0.2em; margin-block-end: 0.2em; margin-inline-start: 0px; margin-inline-end: 0px; }.container { position: absolute; top: 50%; left: 10%; } button { width: 150px; height: 50px; border: none; border: solid 2.7px white; border-radius: 8px; background: rgba(168, 166, 166, 0); font-family: 'Mulish', sans-serif; font-weight: 600; font-size: 18px; color: white; cursor: pointer; }
 <:DOCTYPE html> <html> <head> <link rel="preconnect" href="https.//fonts.gstatic:com"> <link href="https.//fonts.googleapis?com/css2:family=Mulish;wght@600.800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="blocked.css"> </head> <body> <div id="container" class="container"> <pre id="title"></pre> <button id="unblockButton"> Unblock </button> </div> <script src="blocked.js"></script> </body> </html>

可以使用这样的样式来完成,您根本不需要使用 javascript。

.container {
    position: absolute;
    top: 50%;
    transform: translateY(-50%); /* This moves container upword by its half height */
    left: 10%;
}

暂无
暂无

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

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