我正在将一个子元素添加到一个具有固定高度和溢出的容器中:滚动。我希望即使在第一个子元素之前添加元素时内部也不会移动(例如无限滚动)。
我正在尝试设置 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>
最佳答案
有趣的问题!无限滚动将新元素放在前面而不是附加它们有点奇怪,但是好吧,让我们看看。
首先,
$("#parent_insides").scrollTop( new_scroll_y );
不会做任何事情,因为 #parent_insides
不是滚动的 div。 #parent
是,所以我们应该用这个做点什么。但是,我想我找到了一个比所有高度和位置计算更简单的解决方案...:-)
我注意到我的浏览器的默认行为(我使用的是 Chrome)根本不移动内部,只要我不在顶部(如果人们在内容显示时向下滚动,则不会发生这种情况)无论如何添加)。所以我所做的是一个简单的解决方法,我将 #parent
的默认滚动位置设置为偏移“1”,现在,当我单击 ADD 时
按钮,内容不会移动(我保持原样,但顶部添加了蓝色 div):
https://jsfiddle.net/fmsd5b4y/4/
我认为这是预期的浏览器行为:如果我在绝对顶部,内容将向下移动,但如果我向下滚动(即使只是一个像素)我想留在我所在的位置,因此,如果添加内容,我的滚动位置不应该移动。尚未在其他浏览器中对其进行测试,但我认为这是一个很酷的解决方法:-)
关于jquery - 无限卷轴 : set scrollTop() such that page does not shift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43018071/