简体   繁体   English

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

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

When I open a page I want to get full-height background image.当我打开一个页面时,我想获得全高背景图像。 Like this像这样

I haven't started using jQuery yet, so if you could help me with basic js.我还没有开始使用 jQuery,所以如果你能帮助我使用基本的 js。 This is what I tried so far, but it wasn't working.这是我到目前为止尝试过的,但没有奏效。

<!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>

And this is my .js file:这是我的 .js 文件:

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

I did search for this, but couldn't find what I was looking for.我确实搜索过这个,但找不到我要找的东西。 Can you tell me where I was wrong, or provide me with a better code?你能告诉我我错在哪里,或者给我一个更好的代码吗?

Pure CSS Solution纯 CSS 解决方案

No need for JavaScript at all.根本不需要 JavaScript。 Use the vh viewport length unit in your CSS.在 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 CSS 值和单位模块级别 3

This unit specifically sets the length to be equal to a percentage of the v iewport h eight (where 1vh is 1% of the viewport height, etc.) Here you want 100vh (100% of the viewport height):此单元具体设置长度为等于在V iewportħ8(其中的百分比1vh是视口的高度的1%,等)在这里要100vh (视口的高度的100%):

#front-page {
    height: 100vh;
}

An popular answer of mine which I posted to a different question here on Stack Overflow goes into a lot of detail about what the vh unit is: Make div 100% height of browser window .我在 Stack Overflow 上针对不同问题发布的一个流行答案详细介绍了vh单位是什么: Make div 100% height of browser window

You may have noticed that in the example you provided, wordpress.com theme uses a background-size: cover;您可能已经注意到,在您提供的示例中,wordpress.com 主题使用了background-size: cover; for the background image.为背景图像。

See MDN's doc or this friendly tutorial .请参阅MDN 的文档这个友好的教程

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

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