ASP.net Postback – 滚动到特定位置
我有一个ASP.net WebForms页面,屏幕顶部有很多内容。 它有一个链接按钮,将回发到页面并显示页面的另一部分。 当页面刷新时,我想设置焦点并向下滚动到页面的这一部分。
我试过了
txtField.Focus()
在我的代码后面,它将设置焦点并尝试滚动,但然后滚动回到顶部。 焦点仍然在我的文本框上,但屏幕的位置在最顶层。 链接位于屏幕顶部,导致回发。 我想滚动到屏幕的最底部。 它会短暂地执行此操作,然后向右滚动到顶部。
我试过设置
Page.MaintainScrollPositionOnPostback = false;
但这似乎也没有帮助。
有什么方法可以强迫它去特定的位置吗? 当我使用按钮或链接按钮回发时,是否可以向URL添加锚标记?
Page.MaintainScrollPositionOnPostBack = true;
应该让你回到屏幕上的相同位置,但你可以使用AJAX,或者你可以使用SetFocus()
在回发后专注于特定的控件:
如果您有该位置的锚点,则可以使用以下代码:
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);
在你的情况下,我建议你保持Page.MaintainScrollPositionOnPostBack的默认值,并使用纯javascript滚动function
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自动滚动
Page.MaintainScrollPositionOnPostback = true
似乎工作正常。
我已经尝试过Matthieu Charbonnier的答案 ,但除非我补充说它没有用
" 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非常方便指定是否要在屏幕的顶部或底部显示控件。
我有
............ .......
在* .aspx页面上。 在按钮上的* .aspx.cs页面上单击。
Page.SetFocus(mvAriza.ClientID);
它很棒。
这个在asp.net控件中自动滚动到所需的Div这是函数从你想要的地方调用它,也可以下载Java脚本文件
OnClientClick =“return scrollGrid()”
function scrollGrid1(){$(’html,body’)。animate({scrollTop:$(’#Div1’)。offset()。top},’slow’)}