设置div的高度,相对于浏览器窗口的高度 [英] Set height of div, relative to browser window height
问题描述
当前,这将确定窗口高度,并将.one
的高度设置为窗口高度的1/2,将.two
的高度设置为窗口高度的1/4.
Currently this determines window height and sets the height of .one
to 1/2 of the window height, and .two
to 1/4 of the window height.
如何将其重新格式化为使用基于百分比的高度而不是分数?
How could this be reformatted to use a percentage-based heights instead of the fractions?
我想做80%/20%或70%/30%之类的事情.预先感谢.
I'd like to do something like 80%/20% or 70%/30%. Thanks in advance.
$(function(){
$(window).load(function(){
$('.one').css({'height':(($(window).height()/2))+'px'});
$('.two').css({'height':(($(window).height()/4))+'px'});
});
$(window).resize(function(){
$('.one').css({'height':(($(window).height()/2))+'px'});
$('.two').css({'height':(($(window).height()/4))+'px'});
});
});
推荐答案
实际上,我建议首先在两个事件上都获取window
的高度.然后应用简单的数学计算.
Actually I recommend to get the height of window
on both the events first. And then apply the simple math calculations.
$(function(){
$(window).bind("load resize", function(){
_winHeight = $(window).height();
// Setting Height
$('.one').css({'height':_winHeight * 0.5}); // 0.5 = 50%, 0.8 = 80%
$('.two').css({'height':_winHeight * 0.25}); // 0.25 = 25%
});
});
或者您可以将窗口的单位高度存储在变量中,并根据需要应用尽可能多的百分比,例如:
or you can store the unit height of the window in the variable and the apply as much percentage as you want, like:
$(function(){
$(window).bind("load resize", function(){
_winHeight = $(window).height()/100;
// Setting Height
$('.one').css({'height':_winHeight * 50}); // 50% Height
$('.two').css({'height':_winHeight * 25}); // 25% Height
});
});
提示:
- 尝试将load和resize事件绑定在一起,这将节省您的代码长度.
- 此外,jquery中无需提及具有高度的单位px.
祝你好运!快乐的jQuery !!
Good luck! Happy jQuery!!
这篇关于设置div的高度,相对于浏览器窗口的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!