【问题标题】:set div height using jquery (stretch div height)使用 jquery 设置 div 高度(拉伸 div 高度)
【发布时间】:2011-07-29 07:21:34
【问题描述】:

我有 3 个 ID 为 headercontentfooter 的 div。页眉和页脚具有固定的高度,它们的样式设置为浮动在顶部和底部。我想用 jquery 自动计算中间的content 高度。我怎样才能做到这一点??

#header {
    height: 35px;
    width: 100%;
    position: absolute;
    top: 0px;
    z-index: 2;
}
#footer {
    height: 35px;
    width: 100%;
    position: absolute;
    bottom: 0px;
    z-index: 2;
}

提前谢谢...:)

爆破

【问题讨论】:

  • 默认情况下,浏览器不会自动计算div内容的高度吗?
  • 页眉页脚有position:fixed?
  • @Šime,可能适合页眉和页脚之间......
  • 自动 div height=100% 不会在 Firefox 中工作。如果我得到 px 的高度然后我可以减去页眉和页脚的高度,我可以解决这个问题,并且设置上边距会使我的 div 浮动页眉和页脚之间:)
  • @basteralfred 尝试将height: 100% 添加到 html 和 body 标签。那么它应该

标签: jquery css


【解决方案1】:

你可以这样做:

$(function(){

    var $header = $('#header');
    var $footer = $('#footer');
    var $content = $('#content');
    var $window = $(window).on('resize', function(){
       var height = $(this).height() - $header.height() + $footer.height();
       $content.height(height);
    }).trigger('resize'); //on page load

});

在这里看小提琴:http://jsfiddle.net/maniator/JVKbR/
演示:http://jsfiddle.net/maniator/JVKbR/show/

【讨论】:

  • 现在可以了!!我的 jquery 文件有问题。谢谢 :)
  • @blasteralfred 较新版本的 FF 不允许窗口操作,除非用户在他们的偏好中明确允许。
  • 嗨@RobertMullaney,感谢您的更新......但正如尼尔所说,“这些都不是窗口操作”+1 .. :)
  • 抱歉,我一定是在查看尝试脚本大小调整的类似问题时添加了该评论。 PS:没错,虽然它没有修改窗口属性,但从技术上讲,我们通过添加侦听器来操作窗口对象......语义:P
  • 你忘了在$('#header').height() + $('#footer').height() 周围加上括号。 var height 的计算现在不正确了。
【解决方案2】:

正确的做法是使用旧的 CSS:

#content{
    width:100%;
    position:absolute;
    top:35px;
    bottom:35px;
}

而且好处是您不需要附加到 window.onresize 事件!一切都会随着文档重排而调整。一切为了四行CSS的低价!

【讨论】:

  • 这是一个不错的替代方法。我最喜欢 Zirak 的答案,因为这是 OP 要求的(jQuery 答案)。
【解决方案3】:

在我的头顶:

$('#content').height(
    $(window).height() - $('#header').height() - $('#footer').height()
);

你是这个意思吗?

【讨论】:

    【解决方案4】:

    您可以按如下方式绑定函数,而不是在加载时初始化

    $("div").css("height", $(window).height());
    $(​window​).bind("resize",function() {
        $("div").css("height", $(window).height());
    });​​​​
    

    【讨论】:

      【解决方案5】:
      $(document).ready(function(){ contsize();});
      $(window).bind("resize",function(){contsize();});
      
      function contsize()
      {
      var h = window.innerHeight;
      var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/ 
      $('#content').css({"height":calculatecontsize + "px"} );
      }
      

      【讨论】:

        【解决方案6】:

        我认为可行。

        $('#DivID').height('675px');
        

        【讨论】:

          猜你喜欢
          • 2012-09-18
          • 2011-01-19
          • 2010-10-17
          • 1970-01-01
          • 2014-05-22
          • 2013-05-06
          • 2019-06-13
          • 1970-01-01
          • 2011-07-31
          相关资源
          最近更新 更多