繁体   English   中英

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

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

当窗口高于内容高度时,我想在窗口底部固定一个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/

参考OP链接jsfiddle ,这里有一些更改以使代码按预期工作,请参阅注释:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM