ASP.net Postback - 滚动到特定位置

时间:2011-07-12 14:42:29

标签: c# asp.net postback webforms

我有一个ASP.net WebForms页面,屏幕顶部有很多内容。它有一个链接按钮,将回发到页面并显示页面的另一部分。当页面刷新时,我想设置焦点并向下滚动到页面的这一部分。

我试过

txtField.Focus()

在我的代码后面,它将设置焦点并尝试在那里滚动,但然后向右滚动到顶部。焦点仍然在我的文本框上,但屏幕的位置在最顶层。链接位于屏幕顶部,导致回发。我想滚动到屏幕的最底部。它会短暂地执行此操作,然后向右滚动到顶部。

我尝试过设置

Page.MaintainScrollPositionOnPostback = false;

但这似乎也没有帮助。

有什么方法可以强迫它去特定的位置吗? 当我使用按钮或链接按钮回发时,是否可以为URL添加锚标记?

9 个答案:

答案 0 :(得分:29)

如果您有该位置的锚点,则可以使用以下代码:

Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);

答案 1 :(得分:28)

Page.MaintainScrollPositionOnPostBack = true;会让你回到屏幕上的相同位置,但你可以使用AJAX,或者你可以在回发后使用SetFocus()专注于特定的控件:

http://msdn.microsoft.com/en-us/library/ms178232.aspx

答案 2 :(得分:7)

在你的情况下,我建议你保留Page.MaintainScrollPositionOnPostBack的默认值,并使用纯javascript滚动功能

function scrollToDiv()
{
    document.getElementById('yourDiv').scrollIntoView();
}

并在页面启动时调用它,稍微延迟1ms(再次使用纯javascript)

setTimeout(scrollToDiv, 1);

最后用后面的C#代码调用它,使用RegisterStartupScript(在所有页面加载后执行js):

ScriptManager.RegisterStartupScript(Page, typeof(Page), "ScrollToADiv", "setTimeout(scrollToDiv, 1);", true);

像这样,它将绕过任何asp自动滚动

答案 3 :(得分:0)

Page.MaintainScrollPositionOnPostback = true似乎工作正常。

答案 4 :(得分:0)

我已尝试Matthieu Charbonnier answer,但除非我已添加

,否则它无法正常工作
ComboBox
正如http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html

中所建议的那样

我已经创建了一个帮助方法,可以在Chrome,FireFox和IE中使用

" window.scrollTo = function () { };" 

使用getElementById(' {0}')。scrollIntoView比location.hash简单,因为您不需要添加额外的锚元素。

参数alignToTop非常方便指定是否要在屏幕的顶部或底部显示控件。

答案 5 :(得分:0)

我有

<asp:MultiView ID="mvAriza" runat="server">
      <asp:View ID="View14" runat="server"> 
         ............ .......
      </asp:View>
</asp:MultiView>

在* .aspx页面上。在按钮上的* .aspx.cs页面上单击。

Page.SetFocus(mvAriza.ClientID);

效果很好。

答案 6 :(得分:0)

这会自动滚动到asp.net Control中所需的Div 这是功能 从你想要的地方叫它 还下载Java脚本文件

OnClientClick =“return scrollGrid()”

function scrollGrid1(){                 $( 'HTML,身体')。动画                     (                     {                         scrollTop:$('#Div1')。offset()。top                     },                     '慢'                     )         }

答案 7 :(得分:0)

尝试

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) {
            string targetId = Page.Request.Params.Get("__EVENTTARGET");
            Page.ClientScript.RegisterStartupScript(this.GetType(), "focusthis", "document.getElementById('" + targetId + "').focus()", true);

        }
    }

答案 8 :(得分:0)

虽然对您的情况不太满意,但也可以使用虚拟的“自定义验证器”,将要滚动的验证器设置为无效然后执行

DummyCustomValidator.SetFocusOnError = true;

就我而言,我实际上使用的是带有异步回发功能的页面验证器,以及以长垂直形式显示的多个以编程方式显示/隐藏的面板。由于仅当MyLogicalParent.Visible = true且在其他控件(例如在CheckBoxList中选择“其他”时选择了TextBox上的RequiredFieldValidator)中给出了特定答案时才需要某些字段,因此我有很多逻辑来处理页面验证。在所有正常方法中,设置滚动位置都很麻烦。

当异步回发更改页面的垂直尺寸时,我还使用RegisterStartupScript处理维护当前滚动位置。

    <script type="text/javascript">
        $(document).ready(function () {
            var windowHeight = $(document)[0].documentElement.clientHeight;    /*This is the height of the viewable browser area.*/
            var scrolledPosition = $(window)[0].scrollY;                       /*This is the number of Pixels the Window is currently scrolled to.*/
            var scroll = windowHeight + scrolledPosition;                       /*This should be the same as $(window).scrollTop() */
            /*If the amount scrolled + the height of the window is Less than or equal to the total height of the page (past the viewable client window)*/
            if ($(window).scrollTop() + getWindowSize()[1] <= getDocHeight()) {
                /*Move the morescroll div to the bottom of the page... -34 is the height of the div plus a small bottom margin.*/
                $("#morescroll").offset({ top: windowHeight - 34 });
            }
        })

        /*This is the total height of the document including the area past the viewable client window.*/
        function getDocHeight() {
            var D = document;
            /*The Largest of these six numbers is the total doc height. */
            return Math.max(
                D.body.scrollHeight, D.documentElement.scrollHeight,
                D.body.offsetHeight, D.documentElement.offsetHeight,
                D.body.clientHeight, D.documentElement.clientHeight
            );
        }

        /*This is the width and height of the Viewable Browser area.*/
        function getWindowSize() {
            var myWidth = 0, myHeight = 0;
            if (typeof (window.innerWidth) == 'number') {
                //Non-IE
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                //IE 6+ in 'standards compliant mode'
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
            return [myWidth, myHeight];
        }

        //This sets a transparent div <div id="morescroll" class="scrollMinder"> with the text "Scroll down for more." to the bottom of the viewable page. 
        $(window).scroll(
            function () {
                var windowHeight = $(document)[0].documentElement.clientHeight;
                var scrolledPosition = $(window)[0].scrollY;
                var scrll = windowHeight + scrolledPosition;
                document.getElementById('<%= HF_LastScrolled.ClientID %>').value = scrolledPosition;
                var docHeight = $(document)[0].documentElement.scrollHeight;
                /*if we are scrolled to within 60 pixels from the bottom of the document, hide the indicator so it doesn't cover the footer.*/
                if ($(window).scrollTop() + $(window).height() >= $(document).height() - 60) {
                    $("#morescroll").hide();
                }
                /*if we scroll back above 60 pixels from the bottom of the document, show the indicator and set the top of the div to -34 pixels.*/
                else if ($(window).scrollTop() + getWindowSize()[1] <= getDocHeight()) {
                    $("#morescroll").show();
                    $("#morescroll").offset({ top: scrll - 34 });
                }
            });
</script>

     <%-- This stores the Y scroll location.--%>
        <asp:HiddenField ID="HF_LastScrolled" runat="server" />
        <div id="morescroll" class="scrollMinder">
            <span class="spanMinder">Scroll down for more.</span>
        </div>





 private string LastScrolled = "";

    protected void Page_PreRender (object sender, EventArgs e)
            {
                if (string.IsNullOrEmpty(LastScrolled))
                {
                    LastScrolled = "0";
                }
                if (string.IsNullOrEmpty(scrollPosition))
                {
                    sb.Clear();
                    sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                    sb.AppendLine("function EndRequestHandler(sender, args) {");
                    sb.Append("scrollTo(0, ").Append(LastScrolled).Append(");");
                    sb.AppendLine("}");
                    sb.AppendLine("function load() {");
                    sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                    sb.AppendLine("}");
                    cs.RegisterStartupScript(GetType(), "ScrollToLastPosition", sb.ToString(), true);
                    scrollPosition = "ScrollToLastPosition";
                }
                if (!string.IsNullOrEmpty(scrollPosition))
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
                }
            }

    protected void Page_Load (object sender, EventArgs e)
            {
              LastScrolled = HF_LastScrolled.Value;
              Page.MaintainScrollPositionOnPostBack = false;
            }

   protected void SetScrollToLastPosition ()
            {
                sb.Clear();
                sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                sb.AppendLine("function EndRequestHandler(sender, args) {");
                sb.Append("scrollTo(0, ").Append(LastScrolled).AppendLine(");");
                sb.AppendLine("}");
                sb.AppendLine("function load() {");
                sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                sb.AppendLine("}");
                cs.RegisterStartupScript(GetType(), "ScrollToLastPosition", sb.ToString(), true);
                scrollPosition = "ScrollToLastPosition";
                string tempstring = sb.ToString();
                ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
            }

protected void SetScrolltoPositionY (int y)
            {
                sb.Clear();
                sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                sb.AppendLine("function EndRequestHandler(sender, args) {");
                sb.Append("scrollTo(0, ").Append(y).AppendLine(");");
                sb.AppendLine("}");
                sb.AppendLine("function load() {");
                sb.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);");
                sb.AppendLine("}");
                cs.RegisterStartupScript(GetType(), "ScrollTo-0-" + y.ToString(), sb.ToString(), true);
                scrollPosition = "ScrollTo - 0-" + y.ToString();
                string tempstring = sb.ToString();
                ScriptManager.RegisterStartupScript(this, GetType(), scrollPosition, sb.ToString(), true);
            }