// save old window size to adjust only if width changed
let oldWidth = window.innerWidth,
oldHeight = window.innerHeight;
// element to adjust
const target = document.querySelector(".vh100");
// adjust the size if window was resized
window.addEventListener("resize", handleResize);
function handleResize(initial = false) { // the parameter is used for calling the function on page load
/*
* if the width changed then resize
* without this Chrome mobile resizes every time navbar is hidden
*/
if (window.innerWidth !== oldWidth || initial) {
// stretch the target
target.classList.add("setting-100vh");
// save height and apply as min height
const h = target.clientHeight;
target.classList.remove("setting-100vh");
target.style.minHeight = h + "px";
}
}
// call when page is loaded
handleResize(true);
* {
margin: 0;
}
.vh100 {
background-color: green;
}
/*
* Stretch the element to window borders and save the height in JS
*/
.setting-100vh {
position: fixed;
top: 0;
bottom: 0;
min-height: unset;
}
<body>
<header class="vh100">
<h1>100vh on mobile</h1>
</header>
<main>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Possimus ipsa officia mollitia facilis esse cupiditate, nisi recusandae quas id enim alias eaque suscipit voluptates laudantium quasi saepe deserunt labore fuga deleniti placeat, necessitatibus
quibusdam. Quaerat adipisci provident minima laboriosam modi ullam accusamus error dolores iure ducimus laborum similique distinctio temporibus voluptas nulla quod ipsa, nostrum quam cumque id animi unde consectetur incidunt! Dolorem sed quisquam
at cumque. Cumque non nam exercitationem corporis? Minus sed explicabo maiores ipsam ratione. Quam, fugit asperiores nesciunt dolores culpa, numquam blanditiis sint dolorum ex corrupti illo veniam nostrum odio voluptatibus accusantium ullam impedit
eligendi voluptates?</p>
</main>
</body>
.my-element {
height: 100vh; /* Fallback for browsers that do not support Custom Properties */
height: calc(var(--vh, 1vh) * 100);
}
现在让我们用 JavaScript 获得 viewport 的内部高度:
// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);