【问题标题】:ASP.net Postback - Scroll to Specific PositionASP.net 回发 - 滚动到特定位置
【发布时间】:2011-10-03 17:00:02
【问题描述】:

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

我试过了

txtField.Focus()

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

我试过设置

Page.MaintainScrollPositionOnPostback = false;

但这似乎也无济于事。

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

【问题讨论】:

  • 没有。链接位于屏幕顶部。我想滚动到屏幕底部。当我回发它时,它会简短地执行此操作,因为我在控件上调用 Focus() 方法,但由于某种原因,它会向右滚动回顶部。
  • 使用客户端脚本设置焦点。这也将负责滚动控制。
  • 似乎也不起作用。就像我的页面上有一些东西导致它每次都滚动到顶部。想不通。回帖时是否可以在我的网址中添加锚标记?
  • asp.net web 表单中的滚动控件坏了,无法工作。 MaintainScrollPositionOnPostback 是这个有缺陷的系统的一部分。您需要自己设置滚动客户端,有足够的延迟以避免竞争条件......或覆盖微软的 ScriptResource 代码。我最终决定重写他们的 WebForm_AutoFocus 函数是使页面不跳转的唯一方法。

标签: c# asp.net postback webforms


【解决方案1】:

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

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

【讨论】:

  • 如何为页面的不同部分使用 id 属性(锚标记)?您可以在回发后动态填充 Response.Redirect("yourpagewithanchortagrefernece")
  • 最终只使用了一个更新面板,尽管我很讨厌它们:(
  • 它对我不起作用,看看下面对我有用的 ClientScript.RegisterStartupScript(..) 解决方案
  • 是的,Page.MaintainScrollPositionOnPostBack 应该这样做......但它没有。
【解决方案2】:

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

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

【讨论】:

  • @Dismissile 在我看来,这应该被标记为答案。您不必从头开始重新加载页面(因此只有在发生某些回发事件时才能应用代码),而且没有使用已接受的答案,并且据说与所要求的完全相反。
  • 这对我有用,设置 Page.MaintainScrollPositionOnPostBack = false;在特定情况下(因为我的页面通常设置为 true)
  • 这可能会遇到竞态条件。
【解决方案3】:

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

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

并在页面启动时调用它,延迟 1 毫秒(再次纯 javascript)

setTimeout(scrollToDiv, 1);

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

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

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

【讨论】:

    【解决方案4】:

    试试这个

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

    【讨论】:

    • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接。如果没有围绕它们的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请edit你的答案-From Review
    【解决方案5】:

    Page.MaintainScrollPositionOnPostback = true 似乎工作得很好。

    【讨论】:

      【解决方案6】:

      我尝试过Matthieu Charbonnier answer,但除非我添加,否则它不起作用

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

      正如http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html 中所建议的那样

      我创建了一个辅助方法,它可以在 Chrome、FireFox 和 IE 中使用

      public static void ScrollToControl( Page page, string clientId, bool alignToTop)
       {
           //NOTE: if there are more than one call on the page, first one will take preference
           //If we want that last will take  preference, change key from MethodBase.GetCurrentMethod().Name to anchorName
           //recommended in http://gnidesign.blogspot.com.au/2011/06/how-to-maintain-page-scroll-on-postback.html              
           String script = " window.scrollTo = function () { };" + Environment.NewLine;
           script += String.Format("document.getElementById('{0}').scrollIntoView({1});" , clientId, alignToTop.JSToString());
           page.ClientScript.RegisterStartupScript(TypeForClientScript(), MethodBase.GetCurrentMethod().Name, script, true );
           //return script;
       }
       public static string JSToString(this bool bValue)
       {
           return bValue.ToString().ToLower();
       }
      

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

      参数alignToTop很方便指定你想在屏幕顶部还是底部显示控件。

      【讨论】:

        【解决方案7】:

        我有

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

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

        Page.SetFocus(mvAriza.ClientID);
        

        效果很好。

        【讨论】:

          【解决方案8】:

          这会自动滚动到 asp.net 控件中的所需 Div 这是函数 从你想要的地方调用它 并下载 Java 脚本文件

          OnClientClick="return scrollGrid()"

          函数滚动网格1(){ $('html,body').animate ( { scrollTop: $('#Div1').offset().top }, '慢' ) }

          【讨论】:

            【解决方案9】:

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

            DummyCustomValidator.SetFocusOnError = true;
            

            在我的例子中,我实际上是在使用带有异步回发和多个以编程方式显示/隐藏在长垂直表单上的面板的页面验证器。由于仅当 MyLogicalParent.Visible = true 并且在其他控件中给出特定答案时才需要某些字段,例如在 CheckBoxList 中选择“Other”时 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);
                        }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2017-10-05
              • 1970-01-01
              • 1970-01-01
              • 2010-10-11
              • 2023-03-09
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多