简体   繁体   English

使用Javascript计算固定高度导航下包装器div的高度

[英]Using Javascript to calculate the height of a wrapper div under a fixed-height nav

I'm working on my first website and trying to come up with a way to make my wrapper div's height be equal to the height of the browser window minus the fixed-height of the nav menu. 我正在第一个网站上工作,试图找到一种方法,使包装器div的高度等于浏览器窗口的高度减去导航菜单的固定高度。 I first tried a css solution, using: 我首先尝试使用CSS解决方案,方法是:

html body { height: 100% }

and then setting the height of the wrapper div to that value, but it would always make the wrapper div the height of the whole window, including the height of the menu. 然后将wrapper div的高度设置为该值,但这将始终使wrapper div成为整个窗口的高度,包括菜单的高度。 Since I have a fixed value in the menu and would like a variable value for the height of the wrapper (I want .wrapper height = 100vh - 60px), I felt that I couldn't solve this problem using CSS and had to finally face Javascript. 因为我在菜单中有一个固定值,并且想要一个可变的包装高度值(我想.wrapper height = 100vh-60px),所以我觉得我无法使用CSS解决此问题,因此不得不面对Javascript。 So I wrote this code in a separate .js file and referenced in the head of the html document: 因此,我在单独的.js文件中编写了此代码,并在html文档的开头引用了该代码:

var wrapperHeight = {
windowHeight: window.innerHeight,
menuHeight: document.getElementById("sitenav").style.height,
contentHeight: function (windowHeight, menuHeight) {
    return this.windowHeight - this.menuHeight;
}
};
document.getElementByClassName("wrapper").style.height = contentHeight();

There might be a million problems with this code, but what I can't get past is Chrome telling me that document.getElementById("sitenav").style.height is returning null. 这段代码可能有上百万个问题,但是我无法避免的是Chrome告诉我document.getElementById(“ sitenav”)。style.height返回null。 Is this because, when this script is run, the height of #sitenav hasn't been loaded yet? 这是因为在运行此脚本时,尚未加载#sitenav的高度吗? If so, how can I execute this script so that the wrapper displays correctly on loading the page? 如果是这样,我如何执行此脚本,以便包装器在加载页面时正确显示?

Also, if I'm going down the completely wrong path, please let me know. 另外,如果我走的是完全错误的道路,请告诉我。 This is my first experience using Javascript in context, so I apologize if something is blatantly obvious. 这是我在上下文中使用Javascript的第一次经验,因此,如果有任何明显的事情,我深表歉意。

I recommend using jQuery: 我建议使用jQuery:

var windowHeight = $(window).height();
$('body').css('height', windowHeight);

That should do the trick then 那应该可以解决问题

Btw, to use jQuery, paste this on the top of your code: 顺便说一句,要使用jQuery,请将其粘贴到代码顶部:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

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

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