无限滚动:设置scrollTop()使页面不移动

时间:2017-03-25 15:15:15

标签: jquery html css

我将一个子元素添加到具有固定高度和溢出的容器:scroll。我希望即使在第一个孩子之前添加元素时内部也不会移位(如无限滚动)。

我试图设置scrollTop,但它没有任何效果。



$("#button").on("click", function(){
        var height = $("#parent_insides").height();
        var scroll_y =  $("#parent_insides").offset().top;

        $("#parent_insides").prepend( $("#childpre") );
        var new_height = $("#parent_insides").height(); 
        var new_scroll_y =  scroll_y - (new_height - height);

         $("#parent_insides").scrollTop( new_scroll_y );

    })

#parent{
      height:200px;
      overflow:scroll;
    }

    .child1{
      height:300px;
      background:red;
    }

    #childpre{
      height:300px;
      background:blue;
    }

    #button{
        width:200px;
        background:yellow;
        height:40px;
        line-height:40px;
    }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "parent">
        <div id = "parent_insides">
            <div class = "child1">
                hello
            </div>
        </div>
    </div>

    <div id = "button"> Add element above
    </div>

    <div id = "childpre">
        hello
    </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

有趣的问题!对于无限滚动而言,添加新元素而不是附加它们有点奇怪,但好吧,让我们来看看。

首先,

 $("#parent_insides").scrollTop( new_scroll_y );

不会做任何事情,因为#parent_insides不是滚动div。 #parent是,所以我们应该对此做些什么。但是,我认为我找到了比所有高度和位置计算更简单的解决方案......: - )

我注意到我的浏览器的默认行为(我正在使用Chrome)根本就是不改变内部,只要我不在顶部(如果人们在内容时向下滚动则不会发生这种情况反正加了)。所以我所做的是一个简单的解决方法,我将#parent的默认滚动位置设置为偏移'1',现在,当我单击ADD it按钮时,内容执行不要转移(我仍然保持原状,但蓝色div添加在顶部):

https://jsfiddle.net/fmsd5b4y/4/

我认为这是浏览器的行为:如果我在绝对顶部,内容将向下移动,但如果我向下滚动(甚至只有一个像素)我想留在原地,因此,如果内容被添加,我的滚动位置不应该移动。尚未在其他浏览器中测试过,但我认为这是一个很酷的解决方法: - )