如何获取浏览器 window 的高度,然后将 div 的高度设置为该值

How to get height of a browser window and then set a height of a div to that value

当我打开一个页面时,我想获得全高背景图像。 Like this

我还没有开始使用 jQuery,所以如果你能帮助我了解基本的 js。到目前为止,这是我尝试过的方法,但没有用。

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">
    <script type="text/javascript" src="assets/js/basic.js"></script>
    <meta charset="UTF-8"> 
  </head>
  <body>
    <header>
      <div id="front-page" class="window_height_picture" onload="get_window_height()">
      </div>
    </header>
  </body>   
</html>

这是我的 .js 文件:

function get_window_height() {
    var window_height = window.innerHeight;
    document.getElementById('front-page').style.height = window_height + 'px';
}

我确实搜索过这个,但找不到我要找的东西。你能告诉我哪里错了,或者提供更好的代码吗?

纯CSS溶液

根本不需要JavaScript。在 CSS.

中使用 vh 视口长度单位

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.

CSS Values and Units Module Level 3

这个单元具体设置长度等于v视口h八的百分比(其中1vh是视口高度的 1%,等等)在这里你想要 100vh(视口高度的 100%):

#front-page {
    height: 100vh;
}

我在 Stack Overflow 上针对不同问题发布的一个流行答案详细介绍了 vh 单位是什么:Make div 100% height of browser window.

您可能已经注意到,在您提供的示例中,wordpress.com 主题使用 background-size: cover; 作为背景图片。

MDN's doc or this friendly tutorial