jquery - keep window from changing scroll position while prepending items to a list?

前端 未结 6 943
误落风尘
误落风尘 2020-11-29 23:10

I have a page that displays messages and I want it to work just like Facebook, but without the lazy loader. Messages are displayed in chronological order, most recent last.<

6条回答
  •  离开以前
    2020-11-29 23:36

    No need for jQuery here, just check for changes in the elements scrollHeight and adjust the scrollTop accordingly, ie:

    var lastScrollHeight = el.scrollHeight;
    for(var n=0; n<10; n++){
        // Prepend here...
    }
    var scrollDiff = el.scrollHeight - lastScrollHeight;
    el.scrollTop += scrollDiff;
    

    Demo

    http://jsfiddle.net/fkqqv28e/

    jQuery

    To access the native DOM node from a jQuery collection, use array access; ie:

    var lastScrollHeight = $('#myElement')[0].scrollHeight;
    for(var n=0; n<10; n++){
        $('#myElement').prepend('
    prepended '+Math.random()+'
    '); } var scrollDiff = $('#myElement')[0].scrollHeight - lastScrollHeight; $('#myElement')[0].scrollTop += scrollDiff;

提交回复
热议问题