[英]How do I scroll to a newly appended list element with jquery
我正在附加一个新的列表项并尝试将其滚动到视图中。
这是我的HTML:
<div class="slim-scrollbar">
<ul class="chats">
<li class="out">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
</ul>
</div>
我当前的jquery将项添加到列表中:
var direction='out';
$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');
我的jquery尝试:
$(".chats").animate({
scrollTop: ???
}, 1000);
如何将新列表元素滚动到视图中?
要使用您的代码,这应该工作:
$('body,html').animate({
scrollTop: $('.chats li:last-child').offset().top + 'px'
}, 1000);
第1步:确保您已安装scrollTo()
插件 。
步骤2:将附加对象保存在临时变量中,然后滚动主体(或父div,如果在可滚动的div中)。
var newelem = $('<li class="'+direction+'">'+textVar+'</li>');
$('.chats').append(newelem);
$('body').scrollTo(newelem);
如果您真的需要使用jQuery动画,这可能不适合您,但是,您也可以为列表指定一个ID,然后使用本机功能将用户带到新添加的内容。
<ul id="new-stuff" class="chats">
//Append the element and all that good stuff.
location.hash = '#new-stuff';
我建议一个更清洁的解决方案:
var direction = 'out',
lastLi = $("<li/>", {
class: direction,
text: textVar
}).appendTo('.cheats');
$(document).animate({
scrollTop: lastLi.offset().top + 'px'
}, 1000);
假设您的列表位于具有一定高度的包装器div中。
<div id="chatsWrapper" style="height: 200px; overflow:auto;">
<ul class="chats">
<li class="out">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
<li class="in">dynamic text with variable lengths</li>
</ul>
</div>
$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');
只需将包装器div设置为任意高的像素值:
$('#chatsWrapper').animate({ scrollTop: 10000 }, 'normal');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.