设置div的高度,相对于浏览器窗口高度

时间:2013-12-31 17:15:58

标签: javascript jquery

目前,这决定了窗口高度,并将.one的高度设置为窗口高度的1/2,并将.two设置为窗口高度的1/4。

如何重新格式化以使用基于百分比的高度而不是分数?

我想做80%/ 20%或70%/ 30%的事情。提前谢谢。

$(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'});
    });
});

4 个答案:

答案 0 :(得分:1)

为什么不使用CSS?

html, body{
  height: 100%;
}

.one{
    height: 50%;
}

.two {
    height: 25%;
}

答案 1 :(得分:0)

$(function(){
    $(window).load(function(){
        $('.one').css({'height':($(window).height()/2)});
    });
 });

您的编码中没有必要说'px'。它不会产生任何影响..如果不设置它将仅作为像素。要减少50%的高度,您可以将其计算为50/100=1/2。所以上面的编码会降低你的身高50%..相似的25%使用25/100=1/4

答案 2 :(得分:0)

你走了:小提琴:http://jsfiddle.net/Lk7Ve/http://jsfiddle.net/Lk7Ve/2/

这是50%和25%。如果你想要80%和20%,你必须分别乘以(4/5)和(1/5)。

$(document).ready(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'});
});

80%和20%

$(document).ready(function(){
    $('.one').css({'height':(($(window).height() * (4/5)))+'px'});
    $('.two').css({'height':(($(window).height() * (1/5)))+'px'});
});
$(window).resize(function(){
    $('.one').css({'height':(($(window).height() * (4/5)))+'px'});
    $('.two').css({'height':(($(window).height() * (1/5)))+'px'});
});

答案 3 :(得分:0)

实际上我建议先在两个事件上获得window的高度。然后应用简单的数学计算。

$(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%
    });
});

或者您可以将窗口的单位高度存储在变量中,并根据需要应用尽可能多的百分比,例如:

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

提示:

  • 尝试将加载和调整大小事件绑定在一起,这将节省您的代码长度。
  • 此外,没有必要在jquery中提及高度单位px。
祝你好运!快乐的jQuery !!

相关问题