【问题标题】:Change position of div based on content & viewport height using jquery使用jquery根据内容和视口高度更改div的位置
【发布时间】:2015-08-19 07:05:31
【问题描述】:

当窗口高于内容高度时,我希望将 div 固定在窗口底部。如果内容高度高于窗口高度,我希望 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/

【问题讨论】:

    标签: javascript jquery css css-position window-resize


    【解决方案1】:

    参考jsfiddle linked by the OP,这里有一些改动可以让代码按预期工作,请看cmets:

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

    【讨论】:

    • 感谢您的回复,但有些东西不起作用。我将代码插入 jsfiddle (jsfiddle.net/gs5my6ad) - 应该改用 body > viewport 吗?
    • 尝试使用不同版本的 jQuery。它似乎适用于 1.7.2 或更高版本jsfiddle.net/t6h2h4ef/1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2015-06-26
    • 2011-09-27
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多