使用 jquery 根据内容和视口高度更改 div 的位置

Change position of div based on content & viewport height using jquery

当 window 高于内容高度时,我想将 div 固定在 window 的底部。如果内容高度高于 window 高度,我希望 div 位置保持相对。

我目前大部分时间都在使用它,但我根本不希望 div 与内容重叠。我尝试了以下各种形式,但仍然无法正常工作:

var body = content+bottomBar

if (body > viewport) {
    $(".bottom-bar").css({
      'position':'relative'
    });
} else {
  $(".bottom-bar").css({
    'position': 'fixed'
  })
}

我也无法让 window.resize 工作。

如有任何帮助,我们将不胜感激!

http://jsfiddle.net/no05x1vx/1/

参考jsfiddle linked by the OP,这里有一些修改,使代码按预期工作,请看评论:

var content = $(".content").height()
var viewport = $(window).height();

// Use innerHeight here as the bottom-bar div has height 0 and padding 60px
// .height() would return 0
var bottomBar = $(".bottom-bar").innerHeight();
var body = parseInt(content)+parseInt(bottomBar)

$(window).on('resize', function(){
    // Get new viewport height
    viewport = $(window).height();

    if (content > (viewport-bottomBar) ) {
        $(".bottom-bar").css({
            'position':'relative'
        });
    } else {
        $(".bottom-bar").css({
            'position': 'fixed'
        })
    }
});  

// Trigger resize after page load (to avoid repeated code)
$(document).ready(function(){
    $(window).resize();
});