[英]Div Set to Viewport Height, Even When Screen Resized
I am looking to make a div called nav (featured at the very top) take up the entire screen height, even when the screen is resized. 我希望使一个名为nav的div(位于最顶部)在整个屏幕高度上都可以使用,即使在调整屏幕大小时也是如此。 This is the script that Ive included in my index file, but it does not work.
这是Ive包含在索引文件中的脚本,但不起作用。 (I tried working with height: 100vh, but that didn't work for me either.)
(我尝试使用高度:100vh,但这对我也不起作用。)
<script>
$(document).ready(function(){
resizeDiv();
});
window.onresize = function(event) {
resizeDiv();
}
function resizeDiv() {
vpw = $(window).width();
vph = $(window).height();
$('#nav').css({'height': vph + ‘px’});
}
</script>
No need for jScript here. 这里不需要jScript。 I think what you're looking for is the css flexbox-model:
我认为您正在寻找的是CSS flexbox-model:
html, body {
height: 100%;
}
body {
display: flex;
}
#nav {
flex: 1;
}
Havent tried it here, but that one should work for you. Havent在这里尝试过,但是应该为您工作。 Simply add
height: 100%; display: flex
只需增加
height: 100%; display: flex
height: 100%; display: flex
to the parent and flex: 1
on the child element. height: 100%; display: flex
到父元素,而flex: 1
到子元素。
Referring to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ 参考https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Using Jquery you can go with this 使用Jquery可以做到这一点
CSS 的CSS
body {
padding:0;
margin: 0;
}
#nav {
width:100%;
background-color:#abc;
text-align:center;
}
#height {
font-size:20px;
}
HTML 的HTML
<div id="nav">
<span id="height"></span>
</div>
Script 脚本
$(window).on("resize", function(){
var height = $(window).height();
$("#nav").css({ "height": height });
$("span#height").html("the height is " + height);
}).resize();
This should work both on load and resize thanks to the use of the ".resize()" in the last section of the function. 这要归功于加载和调整大小,这要归功于该函数最后一部分中的“ .resize()”。
Keep in mind that "$(window).height()" return the height of the window WITH the horizontal scrollbar, if rendered. 请记住,“ $(window).height()”将使用水平滚动条返回窗口的高度(如果已渲染)。
VH is not fully supported on all the browsers so avoid it for now. 并非所有浏览器都完全支持VH,因此暂时不要使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.