jQuery 根据视口高度动态设置 DIV 高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6564752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:03:39  来源:igfitidea点击:

Set DIV height dynamically based on viewport height

jqueryheightviewport

提问by elbatron

I'm trying to set a div's height to 30% of the viewport height and I would very much like to scale it when the height of the viewport changes.

我正在尝试将 div 的高度设置为视口高度的 30%,我非常想在视口的高度发生变化时对其进行缩放。

I tried setting min-height: 30%; height:30% but it is not working.

我尝试设置 min-height: 30%; 高度:30% 但它不起作用。

I took a look at JQuery's height(); but I just don't know how to get started.

我看了一下JQuery的height(); 但我只是不知道如何开始。

Thanks.

谢谢。

回答by Liam Bailey

function thirty_pc() {
    var height = $(window).height();
    var thirtypc = (30 * height) / 100;
    thirtypc = parseInt(thirtypc) + 'px';
    $("div").css('height',thirtypc);
}

$(document).ready(function() {
    thirty_pc();
    $(window).bind('resize', thirty_pc);
});

回答by Bernd Haug

This is basically Liam Bailey's answer, but with a thirty_pc() that should be both faster and more concise:

这基本上是 Liam Bailey 的回答,但使用了一个应该更快更简洁的 30_pc() :

function thirty_pc() {
    $("div").css('height', '' + Math.round(.3 * window.height()));
}

$(document).ready(function() {
    thirty_pc();
    $(window).bind('resize', thirty_pc);
});

If you like it, please still accept Liam's, but upvote mine. :)

如果你喜欢它,请仍然接受 Liam 的,但请投票给我的。:)

回答by nathan

window.onresize=function(){
    $("#selectedDiv").height( ($(window).height()*.3) );
}

回答by Nikhil Goswami

This one works 100% for viewport height of any div, section that has this class using Jquery. Use additional function to adjust height to 30% currently it is 100% please promote if you like it.

对于使用 Jquery 具有此类的任何 div,部分的视口高度,此方法 100% 有效。使用附加功能将高度调整到 30% 目前它是 100% 如果你喜欢它请推广。

function thirty_pc() {
    $(".introduction").css({'height':($(window).height())+'px'});
}

$(document).ready(function() {
    thirty_pc();
    $(window).bind('resize', thirty_pc);
});