1

I'm appending a new list item and trying to scroll it into view.

Here is my 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:

var direction='out';

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

My jquery attempt:

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

How do I scroll the new list element into view?

4

5 回答 5

4

To use your code, this should work:

$('body,html').animate({
    scrollTop: $('.chats li:last-child').offset().top + 'px'
}, 1000);
于 2013-07-19T13:53:36.490 回答
0

Step 1: make sure you've got the scrollTo() plugin installed.

Step 2: Save the appended object in a temporary variable, then scroll the body (or parent div, if in a scrollable div).

var newelem = $('<li class="'+direction+'">'+textVar+'</li>');
$('.chats').append(newelem);
$('body').scrollTo(newelem);
于 2013-07-19T13:50:51.697 回答
0

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.

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

//Append the element and all that good stuff.

location.hash = '#new-stuff';
于 2013-07-19T13:55:18.903 回答
0

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);
于 2013-07-19T13:58:28.990 回答
0

Assuming your list is inside a wrapper div with some height.

<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:

$('#chatsWrapper').animate({ scrollTop: 10000 }, 'normal');
于 2013-07-19T13:58:38.670 回答