Restoring page scroll position with jQuery

后端 未结 6 1346
春和景丽
春和景丽 2020-12-05 17:21

I have a page operation that uses something like:

$(\'#thetable tbody\').replaceWith(newtbody);

in an ajax callback. Sometimes, if the user

相关标签:
6条回答
  • 2020-12-05 17:36
    var position= $(window).scrollTop();
    
    //some things here
    
    $(window).scrollTop(position);
    

    It worked for me in both IE8 and FF.

    0 讨论(0)
  • 2020-12-05 17:38

    Try to use .html() instead of .replaceWith():

    $('#thetable tbody').html( newtbody.html() );.

    I don't know about possible performance bottlenecks here, but it did the trick for me when I was trying to preserve the scroll position of a div, and it seems to do well with the scroll position of the entire page as well.

    0 讨论(0)
  • 2020-12-05 17:40

    Be sure to use return false; to terminate your function(){} construct.

    The event trigger may be trying to execute the default action of the target DOM element i.e., < a href="" >;

    0 讨论(0)
  • 2020-12-05 17:44

    We had the exact same problem, and the following code works great...

    var scroll = $(window).scrollTop();
    // yada
    $("html").scrollTop(scroll);
    
    0 讨论(0)
  • 2020-12-05 17:55

    You could periodically check the div outerHeight, and set the scrollTop property once the div rendering has crossed the scroll value.

    var g_Interval ;
    var g_ScrollTop ;
    
    function checkAndAdjustScroll() {
        var height=$('#content').outerHeight() ;
        if(height>g_ScrollTop) {
                $(window).scrollTop(g_ScrollTop) ;
                clearInterval(g_Interval) ;
        }
    }
    

    And whenever you update your div with AJAX content, do this

    g_ScrollTop=$(window).scrollTop() ;
    g_Interval=setInterval(checkAndAdjustScroll, 100) ;
    

    You might need to make adjustments based on the offset of your div from the top of the page

    0 讨论(0)
  • 2020-12-05 18:01

    Are u use aspx? if it's aspx:

    $(document).ready(function () {
            //------------ scroll-------------
             
            $('body').scrollTop(document.getElementById('<%=hdScroll.ClientID%>').value);
                
            $(window).scroll(function () {
                $("#<%= hdScroll.ClientID %>").val($(window).scrollTop());
                //alert(document.getElementById('<%=hdScroll.ClientID%>').value);
            });
           });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <asp:HiddenField Id="hdScroll" runat="server"></asp:HiddenField>

    0 讨论(0)
提交回复
热议问题