How do I maintain scroll position in MVC?

后端 未结 12 1957
情歌与酒
情歌与酒 2020-11-27 18:02

Im working on a project in MVC and have enjoyed learning about it. There are a few growing pains but once you figure them out it\'s not bad. One thing that is really simpl

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 18:48

    Here's a simple, pure Javascript solution which I've tested in FF4 and IE9 only.

    The idea is that this solution should degrade gracefully by falling back to the standard #anchor tags on a page. What I'm doing is replacing those #anchor tags on the fly with the X and Y coordinates, then on load, I simply read those values from the querystring and scroll there. If this fails for some reason, the browser should still navigate to the #anchor position...

    Markup:

    My Link
    

    jQuery:

    $(function() {
    
    // RESTORE SCROLL POSITION
    RestoreScrollPosition();
    
    // SAVE SCROLL POSITION
    $('a:not(a[href^="http"])').filter('[href$="#someanchor"]').each(function() {
        $(this).click(function() {
            var href = $(this).attr('href').replace("#someanchor","");
            if (href.indexOf('?') == -1) {
                href = href + '?x='
            } else {
                href = href + '&x='
            }
            href = href + window.pageXOffset;
            href = href + '&y=' + window.pageYOffset;
            $(this).attr('href', href);
        });
    });
    }
    

    A couple of helper methods:

    function RestoreScrollPosition() {
    
        var scrollX = gup('x');
        var scrollY = gup('y');
    
        if (scrollX != null && scrollY != null) {
            window.scrollTo(scrollX, scrollY);
            return true;
        }
        return false;
    }
    
    function gup(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null)
            return "";
        else
            return results[1];
    }
    

    This fits my needs, but could be more generic/reusable - I'd be happy for someone to improve on this... :-)

提交回复
热议问题