How to keep whole page scroll position after asynchronous postback

眉间皱痕 提交于 2019-12-01 12:32:45

问题


i am using asp.net 4.0 iis 7.5 microsoft visual studio 2010

what i want is keep whole page (browser) scroll position (not a div or panel) when asynchronous postback happened (update panel)

how can i do this

actually i had a function which can keep div scroll bar position after postback like this

       <script type="text/javascript">
        var xPos, yPos;
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_beginRequest(BeginRequestHandler);
        prm.add_endRequest(EndRequestHandler);
        function BeginRequestHandler(sender, args) {
            xPos = document.getElementById('Main').scrollLeft;
            yPos = document.getElementById('Main').scrollTop;
        }
        function EndRequestHandler(sender, args) {
            document.getElementById('Main').scrollLeft = xPos;
            document.getElementById('Main').scrollTop = yPos;
        }
    </script>

bu i could not find browser scroll bar id to get its values to get with document.getElementById

thanks for answers


回答1:


asp.net has @page directive property called MaintainScrollPositionOnPostBack

hope this will help




回答2:


I found it here :http://forums.asp.net/t/1300961.aspx

just add it right after script manager. it works for me in all browsers

<script type="text/javascript">
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(beginRequest);
    function beginRequest()
    {
        prm._scrollPosition = null;
    }
</script>



回答3:


You can do it the client way :

$(document).ready(function () {
    $(window).on('beforeunload', function () {
        document.cookie = "keepscroll=" + $(window).scrollTop();
    });
    var cs = document.cookie ? document.cookie.split(';') : [];
    var i = 0, cslen = cs.length;
    for (; i < cs.length; i++) {
        var c = cs[i].split('=');
        if (c[0].trim() == "keepscroll") {
            $(window).scrollTop(parseInt(c[1]));
            break;
        }
    }
});

If you are not jQuery's friend then you could try something like :

window.onbeforeunload = function () {
    document.cookie = "keepscroll=" + document.body.scrollTop;
};
var keepscroll = window.setTimeout(function () {
    var cs = document.cookie ? document.cookie.split(';') : [];
    var i = 0, cslen = cs.length;
    for (; i < cs.length; i++) {
        var c = cs[i].split('=');
        if (c[0].trim() == "keepscroll") {
            window.scrollTo(0, parseInt(c[1]));
            break;
        }
    }
    window.clearTimeout(keepscroll);
    keepscroll = null;
}, 100);


来源:https://stackoverflow.com/questions/3948417/how-to-keep-whole-page-scroll-position-after-asynchronous-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!