Set DIV height dynamically based on viewport height

假如想象 提交于 2019-12-03 06:06:37

问题


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.

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

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

Thanks.


回答1:


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);
});



回答2:


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

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. :)




回答3:


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



回答4:


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.

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

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


来源:https://stackoverflow.com/questions/6564752/set-div-height-dynamically-based-on-viewport-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!