简体   繁体   English

javascript scrollTop似乎不起作用

[英]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. 我使用一种技术,我在div中有一个表,以限制表所覆盖的空间并滚动。 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. 单击一个时,表将在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. 所以在我用javascript渲染表之后,我执行了一个setTimeout调用来异步调用一个函数,该函数将scrollTop值设置回重新渲染之前的位置。 Here's the code snipit in question: 这是有问题的代码片段:

Note: (ge() == geMaybe() == document.getElementById()) 注意:(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. 请注意,我将超时设置为一整秒,以确保在调用滚动代码时将渲染移动到DOM。 I am using chrome mainly but need it to eventually work cross-browser. 我主要使用chrome,但最终需要它才能跨浏览器工作。 I don't use jQuery. 我不使用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. 如果我尝试在调试器中捕获onscroll事件,甚至从onscroll处理程序记录内容,则当使用鼠标移动滚动条时,chrome调试器会崩溃。

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);
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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