停止在固定div内滚动

时间:2015-01-13 19:58:55

标签: html scroll fixed sticky

我有2个div(一个是固定的,另一个是相对的) 我在固定的内部实现滚动行为...与页面一起滚动。我想要做的更多是当固定的一个div滚动到底部时,这应该停止滚动,只有页面应该继续滚动。 我不知道我是否非常清楚这就是为什么我创建一个fiddle

<style>

body {
  background-color:#dddddd;
  margin: 0;
}

#mainDiv{
    top: 120px;
    max-width: 1024px;
    margin:0px auto;
    background-color:#fff;
}

#leftDiv{
    width: 30%;
    float: left;
    background-color: #DBEAED;
    height: 300px;
    top: 1em;
    z-index: 999;
    position: fixed;
    overflow: hidden;
}
#rightDiv{
    width: 68%;
    padding-left: 2%;
    float: right;
    background-color: #FBE9DD;
}
#filters{
    display: inline-block;
}
</style>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
 <script>
 $(document).ready(function () {
            window.onscroll = scrollFunction;
            function scrollFunction() {
                var doc = document.documentElement, body = document.body;
                var top = (doc && doc.scrollTop || body && body.scrollTop || 0);;

                $('#filters').css("margin-top", -top);
            }
        });
 </script>
<div id="mainDiv">
    <div id="leftDiv">
        <div id="filters">
            <p>XX 1</p><p>XX 2</p><p>XX 3</p><p>XX 4</p><p>XX 5</p><p>XX 6</p><p>XX 7</p><p>XX 8</p><p>XX 9</p><p>XX 10</p><p>XX 11</p><p>XX 12</p>
        </div>
    </div>
    <div id="rightDiv">
        Here is PLP page
        <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p>
        <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p>
        <p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p><p>a</p>
    </div>
</div>

任何帮助都非常受欢迎。谢谢 !!! PS。 X12应该粘在蓝色区域的末端。

1 个答案:

答案 0 :(得分:0)

如果我不正确,请将其设置为top的最大值为$('#filters').height()-$('#leftDiv').height(),这是您希望过滤器滚动的最大值。此外,为了能够优雅地改变方向,而不是将#filters的边距设置为等于滚动顶部,我们必须在滚动时递增和递减值

$(document).ready(function () {
    window.onscroll = scrollFunction;
    var filterMargin = 0;
    maxTop = $('#filters').height() - $('#leftDiv').height();
    lastTop = 0;

    function scrollFunction() {

        var doc = document.documentElement, body = document.body;
        var top = (doc && doc.scrollTop || body && body.scrollTop || 0);

        filterMargin = -parseInt($('#filters').css("margin-top"));

        var diff = top - lastTop;

        filterMargin += diff;
        //make sure the margin value stops when the scrolling stops,
        //otherwise the scrolling physically stops but the value keeps growing
        filterMargin = filterMargin < 0 ? 0 : filterMargin;
        filterMargin = filterMargin > maxTop ? maxTop : filterMargin;
        console.log(top, maxTop, filterMargin, top - lastTop);
        $('#filters').css("margin-top", -filterMargin + 'px');
        lastTop = top;
    }

});

小提琴: http://jsfiddle.net/nfp6fhg6/5/

相关问题