简体   繁体   English

如何使用jquery滚动到新添加的列表元素

[英]How do I scroll to a newly appended list element with jquery

I'm appending a new list item and trying to scroll it into view. 我正在附加一个新的列表项并尝试将其滚动到视图中。

Here is my HTML: 这是我的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>

My current jquery to append an item to the list: 我当前的jquery将项添加到列表中:

var direction='out';

$('.chats').append('<li class="'+direction+'">'+textVar+'</li>');   

My jquery attempt: 我的jquery尝试:

    $(".chats").animate({
        scrollTop: ???
    }, 1000);

How do I scroll the new list element into view? 如何将新列表元素滚动到视图中?

To use your code, this should work: 要使用您的代码,这应该工作:

$('body,html').animate({
    scrollTop: $('.chats li:last-child').offset().top + 'px'
}, 1000);

Step 1: make sure you've got the scrollTo() plugin installed. 第1步:确保您已安装scrollTo()插件

Step 2: Save the appended object in a temporary variable, then scroll the body (or parent div, if in a scrollable div). 步骤2:将附加对象保存在临时变量中,然后滚动主体(或父div,如果在可滚动的div中)。

var newelem = $('<li class="'+direction+'">'+textVar+'</li>');
$('.chats').append(newelem);
$('body').scrollTo(newelem);

This may not be an option for you if you really need to use the jQuery animation, but, you could also give your list an id and then use native functionality to get the user to the newly added content. 如果您真的需要使用jQuery动画,这可能不适合您,但是,您也可以为列表指定一个ID,然后使用本机功能将用户带到新添加的内容。

<ul id="new-stuff" class="chats">

//Append the element and all that good stuff.

location.hash = '#new-stuff';

I would suggest a cleaner solution: 我建议一个更清洁的解决方案:

var direction = 'out',
    lastLi = $("<li/>", {
        class: direction,
        text: textVar
    }).appendTo('.cheats');
$(document).animate({
    scrollTop: lastLi.offset().top + 'px'
}, 1000);

Assuming your list is inside a wrapper div with some height. 假设您的列表位于具有一定高度的包装器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>'); 

Just animate the wrapper div to an arbitrarily high pixel value: 只需将包装器div设置为任意高的像素值:

$('#chatsWrapper').animate({ scrollTop: 10000 }, 'normal');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM