Вопрос

I have googled around and found a few solutions to this problem, but none of them seem to work in my situation. I have tried hidden inputs to scroll to, that stay at the bottom

document.getElementById('scrollToMe').scrollIntoView();

I have tried

$("#postbox").scrollTop($("#postbox")[0].scrollHeight);

and a few others. Here is my situation

I have a chat room (http://novaplasm.topiacloud.com/Chat). When you type anything, it enters it into the div "postbox" using Knockout. Every time you enter new content, it appends it. I want to make it so you can always see the latest message, without having to scroll yourself. I can't seem to do this for the life of me. Thanks in advanced!

Это было полезно?

Решение

First get a reference to your postbox and chat message div

   var pbox = $('#postbox');

   var chat_div = $('<div></div>').attr('class', 'chat_msg').text(msg);

Here msg is your chat message

Then you have to scroll down using the 'animate' method like this

  chat_div.appendTo(pbox);

   var height = pbox.scrollTop() + pbox.height() +  $('#postbox').filter('.chat_msg:last').scrollTop();

   pbox.animate({'scrollTop' : height}, 1000);

Here the animation is happening over 1 sec.

Refer jQuery documentation for more detailed explanations on jQuery methods.

Live fiddle example

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top