I have a div that contains a list of messages (it's a chatroom application). As each message is added to the bottom of the list, I think I want the div to be scrolled to the bottom of the page. That make sense, right? So - questions #1: how do I get the div to scroll to the bottom?

Now, the next question is a bit about usability. What if the user scrolls up to read something that was previously posted? Then suddenly someone posts a new message? That means the jQuery will scroll down again. This can be very irritating to the user. What's a good way to handle this? Should it only scroll down if the scroll bar is scrolled all the way down already before a new message is added? If so, how to do that in jQuery? Or is there a more usable solution?

有帮助吗?

解决方案

you can get the position of the scrollbar by window.pageYOffset and then use window.scrollTo(0, y) to scroll to some place.

or you can even use $('#mydiv').scrollTop(newmsg_top) in jquery to scroll down to the new message.

where var newmsg_top = parseInt($('#mydiv li:last').offset().top);

here #mydiv is the div with all your messages.
so #mydiv li:last points to the last message.
offset() returns the current position of the element with respect to the document and you can get the top position by .top

If you want the relative position with respect to the parent instead you can go with position()

EDIT : Got a jsfiddle working here here. Please take a look. Note : You go down only if you are viewing the last element.(for the solution of your usability issue)

其他提示

// this is will scroll to the end, after append

$("#mydiv").append("My data");
var newmsg_top = parseInt($('#mydiv')[0].scrollHeight );
$('#mydiv').scrollTop(newmsg_top);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top