简体   繁体   中英

javascript scrollTop doesn't seem to work

I use a technique where I have a table within a div so as to limit the space covered by the table and scroll instead. Within the table are checkboxes. These checkboxes effect how the table is rendered. When one is clicked, the table is re-rendered within the div. This always causes the scrollbar to go back to the top which is annoying. So after I render the table in javascript I do a setTimeout call to asynchronously call a function that sets the scrollTop value back to where it was before the re-render. Here's the code snipit in question:

Note: (ge() == geMaybe() == document.getElementById())

o.renderAndScroll = function() {
    var eTestSection = geMaybe(o.id + '-testSection');
    var scrollTop = 0;
    if (eTestSection) {
        scrollTop = eTestSection.scrollTop;
    }

    o.render();

    if (eTestSection) {
       setTimeout(
           function() { 
               console.log('Scrolling from ' + ge(o.id).scrollTop + ' to ' + scrollTop);
               ge(o.id).scrollTop = scrollTop;
               console.log('Scrolled to ' + ge(o.id).scrollTop);
          }, 
          1000);
    }            
}

My console log output is this each time I change a checkbox state:

Scrolling from 0 to 1357
Scrolled to 0

Any other way to make this work? Note that I made the timeout a full second just to make sure the render was moved to the DOM by the time my scroll code is called. I am using chrome mainly but need it to eventually work cross-browser. I don't use jQuery. If I try to catch the onscroll event in the debugger or even log stuff from an onscroll handler, the chrome debugger crashes when the scrollbar is moved with the mouse.

The correct code is:

o.renderAndScroll = function(fForce) {
        var scrollTop = 0;
        var eTestSection = geMaybe(o.id + '-testSection');
        if (eTestSection) {
            scrollTop = eTestSection.scrollTop;
        }
        o.render(fForce);
        setTimeout(
            function() {
                // re-lookup element after being rendered
                var eNewTestSection = ge(o.id + '-testSection');
                eNewTestSection.scrollTop = scrollTop;
            },
            1);
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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