粘性侧边栏20px顶部尺寸

时间:2019-07-31 15:54:10

标签: javascript html css sticky

enter image description here

TEST PAGE

我试图使侧边栏的垂直线的顶部停止在顶部导航(已附加示例图像),我试图在js代码中添加'top': '20',但没有成功。我也在CSS中尝试了margin-top: 20px,但并没有解决问题。我不确定在哪里可以在侧边栏上方添加20px的高度。


JavaScript

$(document).ready(function () {

var length = $('#community-sidebar').height() - $('#community-section-col1').height() + $('#community-sidebar').offset().top;

$(window).scroll(function () {

    var scroll = $(this).scrollTop();
    var height = $('#community-section-col1').height() + 'px';

    if (scroll < $('#community-sidebar').offset().top)  {

        $('#community-section-col1').css({
            'position': 'absolute',
            'top': '0'
        });

    } else if (scroll > length) {

        $('#community-section-col1').css({
            'position': 'absolute',
            'bottom': '0',
            'top': 'auto'
        });

    } else {

        $('#community-section-col1').css({
            'position': 'fixed',
            'top': '0',
            'height': height
        });

    }
});

});

CSS

#community-sidebar {left: -45px; position: absolute; top: -40px; height: 1500px;}
.h-line { border-left: solid black 1px; height: 550px; border-width: thin; width: 1px; left: 189px; position: absolute; top: 0;}

1 个答案:

答案 0 :(得分:1)

用高度为20px的div包裹标题,后跟标题为position:fixed

<div style="height:20px">
  <div style="position:fixed">
    //your header content
  </div>
</div>