即使向其添加内容,也要将滚动条固定到底部 [英] Make the scrollbar fixed to bottom even while appending content to it
本文介绍了即使向其添加内容,也要将滚动条固定到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了更好地理解,我正在尝试实现聊天框,以平滑过渡上一个(上方)聊天消息。
For better understanding I am trying to implement chatbox with smooth transition of previous (upper) chat messages.
当我点击添加时,我想要所有数字1 - 9向上滑动并在其下方附加10-12。
When I click "Add" I want all the number 1 - 9 slide up and append 10-12 below it.
或者换句话说我希望滚动条始终在底部滚动修复。
Or in other word I want the scrollbar always scrolled fix at bottom.
我知道我可以在追加后重新定位滚动条但是我将无法看到滑动动画。
I know that I can reposition the scrollbar after appending but then I will not able to see sliding animation.
代码参考
$(document).ready(function(){
// set the default scroll bar to bottom of chat box
$(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
$("button").click(function(){
$('.chat-list li:last-child').append('10<br/>11<br/>12');
$('.chat-list li:last-child').show('slow');
});
});
<ul class="chat-list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li style="display:none"></li>
</ul>
<button>add</button>
.chat-list{
height:100px;
overflow:auto;
}
推荐答案
$(document).ready(function(){
// set the default scroll bar to bottom of chat box
$(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
$("button").click(function(){
$('.chat-list li:last-child').append('10<br/>11<br/>12');
// Do a callback for show()
$('.chat-list li:last-child').show('slow', function() {
$(".chat-list").scrollTop($(".chat-list")[0].scrollHeight);
});
});
});
回调 show()
哪个将 scrollTop()
转换为 $('。chat-list')[0] .scrollHeight
。
如果你想要一个动画,那么只需为scrollTop属性设置动画:
If you want to have an animation then just animate scrollTop property:
$(".chat-list").animate({
scrollTop: $(".chat-list")[0].scrollHeight
},'slow');
这篇关于即使向其添加内容,也要将滚动条固定到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文