到达新div时停止粘性div

时间:2015-02-06 12:00:49

标签: javascript jquery html css sticky-windows

我有一个粘贴的盒子,一旦我们滚过一个div就会粘住,现在我希望一旦它到达一个新的div就阻止这个盒子粘。

<div id="sticky-anchor"></div>
    <div id="sticky">
        box
    </div>
    <div>             
        content that box scrolls on top
    </div>
    <div id="stop-anchor"></div>
    <div>
        other content that I do not with to have the sticky area in
    </div>
#sticky.stick {
    top: 113px;
    padding: 36px 0 36px 0;
    z-index: 10000;
    background-color: $white;
    position: fixed;
    width: 60%;
    left: 20%;
}
function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    if (window_top > div_top) {
        $('#sticky').addClass('stick');
    }
    else {
        $('#sticky').removeClass('stick');
    }
}

$(function () {
    $(window).scroll(sticky_relocate);
    sticky_relocate();
});

我希望这很清楚,非常感谢。

1 个答案:

答案 0 :(得分:2)

您需要稍微调整一下javascript代码,以便检查您到达anchor-stop div的时间:

function sticky_relocate() {
    var window_top = $(window).scrollTop();
    var div_top = $('#sticky-anchor').offset().top;
    var stop_top = $('#stop-anchor').offset().top;
    if (window_top > div_top && window_top < stop_top) {
        $('#sticky').addClass('stick');
    }
    else {
        $('#sticky').removeClass('stick');
    }
}

$(document).ready(function () {
    $(window).scroll(sticky_relocate);
});

这应该可以解决问题。