【问题标题】:Calculate the height of body计算身体的高度
【发布时间】:2017-01-27 14:04:19
【问题描述】:

这是我的JS FIDDLE

我有一页包含不同的元素。 这些元素在某个滚动位置将它们的位置“固定”更改为“绝对”。

问题是我的身高。由于固定元素,它在我的身上没有“自动”高度。所以我放了一个 min-height : 1000px 例如。但它不是正确的解决方案...... 滚动时滚动条的大小会发生变化,我希望主体覆盖我的所有元素。

也许我必须在没有固定元素的情况下在开始时计算我的身体高度?

 $('body').css({scrollTop:$(document).height() + $(window).height()});

我试过了,但它不起作用......

$(document).ready(function() {

  $('body').css({
    scrollTop: $(document).height() + $(window).height()
  });

  var windw = this;

  $.fn.followTo = function(pos) {
    var $this = this,
      $window = $(windw);

    $window.scroll(function(e) {
      if ($window.scrollTop() > pos) {
        $this.css({
          position: 'absolute',
          top: pos
        });
      } else {
        $this.css({
          position: 'fixed',
          top: 0
        });
      }
    });
  };

  $('h1').followTo(400);

  $('.two').followTo(350);
});

【问题讨论】:

    标签: jquery html css


    【解决方案1】:

    如果我明白你的意思,你希望body 元素将所有 div 包装在页面中,无论它们是固定定位还是绝对定位,对吗?

    如果是这样,您可以尝试使用这种非常硬编码的解决方案,通过添加每个 div 的高度(包括其垂直边距)来计算主体的高度。

    所以不要这样做:

    $('body').css({scrollTop:$(document).height() + $(window).height()});
    

    你可以这样做:

    var totalOneHeight = $('.one').height() + parseInt($('.one').css('marginTop'));
    var totalTwoHeight = $('.two').height() + parseInt($('.two').css('marginTop'));
    var totalHeight = totalOneHeight + totalTwoHeight;
    $('body').css({'height': totalHeight});
    

    当然,这是一个非常硬编码的解决方案,所以如果您打算向页面添加更多内容,请记住在 sum 中添加项目。

    我使用.css('marginTop') 获取元素的marginTop,由parseInt() 包围,因为前面的方法也返回单位(px)。

    编辑:以防万一你想知道,如果你添加 marginBottom 你也应该把它放到总和中

    尝试解决方案here

    【讨论】:

      【解决方案2】:

      我认为这可以解决您的问题

      #footer {
              padding: 20px 0;
              position: fixed;
              bottom: 0;
              width: 100%;
              z-index: 15000;
          }
      

      【讨论】:

      猜你喜欢
      • 2017-03-22
      • 2011-05-29
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-07
      • 1970-01-01
      • 2011-11-10
      • 2013-05-15
      相关资源
      最近更新 更多