当滚动位置距离窗口顶部 85px 时修复 div

JPB*_*JPB 2 html javascript css jquery

当向下滚动时“middle_block2”到达“top_block”的底部时,我需要将“middle_block2”固定到固定位置“top_block”的底部或距窗口顶部85px(“top_block”的高度)。这是代码和 jsfiddle 的链接。

当它到达窗口顶部时我就让它工作了,但这是我所能达到的。

jsfiddle: https: //jsfiddle.net/jpolsonb/u9adhkc7/1/

超文本标记语言

<div class='top_block'>
<p>Top Block</p>
</div>

<div class='middle_block1'>
<p>Middle Block 1</p>
</div>

<div class ='ghost_div'>
<div class='middle_block2'>
<p>Middle Block 2</p>
</div>
</div>

<div class='bottom_block'>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
<p>Bottom Block</p>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS

* {
margin:0;
padding:0;
}

.top_block {
width:100%;
background-color: black;
height: 85px;
color:white;
padding: 0px;
margin: 0px;
position:fixed;
}


.middle_block1 {
width:100%;
background-color: yellow;
height: 450px;
color:black;
padding-top: 85px;
z-index:2;
}

.ghost_div {
height: 85px;
background-color: red;
}

.middle_block2 {
width:100%;
background-color: blue;
height: 85px;
color:white;
}

.bottom_block {
width:100%;
background-color: red;
height: 950px;
color:white;
}
Run Code Online (Sandbox Code Playgroud)

查询

$(function(){
    // Check the initial Position of the fixed_nav_container
    var stickyHeaderTop = $('.middle_block2').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('.middle_block2').css({position: 'fixed', top: '85px'});  
            } else {
                    $('.middle_block2').css({position: 'relative', top: '0px'});
            }
    });
});
Run Code Online (Sandbox Code Playgroud)

Saj*_*lly 5

请像这样修改代码并检查

$(function(){
    // Check the initial Position of the fixed_nav_container
    var stickyHeaderTop = $('.middle_block2').offset().top;

    $(window).scroll(function(){
        if( $(document).scrollTop() > stickyHeaderTop-85 ) {
            $('.middle_block2').css({position: 'fixed', top: '85px'});  
        } else {
            $('.middle_block2').css({position: 'relative', top: '0px'});
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

更新的小提琴:https://jsfiddle.net/u9adhkc7/4/