C# ASP.net回发-滚动到特定位置
我有一个ASP.net WebForms页面,在屏幕顶部有很多内容。它有一个链接按钮,可以发回页面并显示页面的另一部分。当页面刷新时,我想设置焦点并向下滚动到页面的这一部分 我试过了C# ASP.net回发-滚动到特定位置,c#,asp.net,postback,webforms,C#,Asp.net,Postback,Webforms,我有一个ASP.net WebForms页面,在屏幕顶部有很多内容。它有一个链接按钮,可以发回页面并显示页面的另一部分。当页面刷新时,我想设置焦点并向下滚动到页面的这一部分 我试过了 txtField.Focus() 在我的代码后面,它将设置焦点并尝试在那里滚动,但然后向右滚动回到顶部。焦点仍然在我的文本框上,但屏幕的位置在最顶端。链接位于导致回发的屏幕顶部。我想滚动到屏幕的最底部。它会简单地执行此操作,然后向右滚动回到顶部 我试过了 Page.MaintainScrollPositionOn
txtField.Focus()
在我的代码后面,它将设置焦点并尝试在那里滚动,但然后向右滚动回到顶部。焦点仍然在我的文本框上,但屏幕的位置在最顶端。链接位于导致回发的屏幕顶部。我想滚动到屏幕的最底部。它会简单地执行此操作,然后向右滚动回到顶部
我试过了
Page.MaintainScrollPositionOnPostback = false;
但这似乎也没什么帮助
有什么办法可以强迫它去一个特定的位置吗?
当我使用按钮或链接按钮回发时,是否可以向URL添加锚定标记?
Page.MaintainScrollPositionOnPostBack=true
应将您带回屏幕上的相同位置,但您可以使用AJAX,也可以在回发后使用SetFocus()
关注特定控件:
Page.MaintainScrollPositionOnPostback=true
似乎工作正常。如果您有定位点,可以使用以下代码:
Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);
在您的情况下,我建议您保留Page.MaintainScrollPositionOnPostBack的默认值,并使用纯javascript滚动功能
function scrollToDiv()
{
document.getElementById('yourDiv').scrollIntoView();
}
并在页面启动时以1ms的延迟调用它(再次使用纯javascript)
最后,使用RegisterStartupScript(在加载所有页面后执行js)从C#代码后面调用它:
这样,它将绕过我尝试过的任何asp自动滚动,但除非我添加了
" window.scrollTo = function () { };"
正如在报告中所建议的那样
我已经创建了一个helper方法,它在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非常方便指定您希望在屏幕的顶部还是底部显示控件。我有
<asp:MultiView ID="mvAriza" runat="server">
<asp:View ID="View14" runat="server">
............ .......
</asp:View>
</asp:MultiView>
它工作得很好。在asp.net控件中自动滚动到所需的Div 这是函数 从你想要的地方打电话 并下载Java脚本文件 OnClientClick=“return scrollGrid()” 函数scrollGrid1(){ $('html,body')。设置动画 ( { scrollTop:$('#Div1').offset().top }, “慢” ) }试试这个
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);
}
}
虽然不适合您的情况,但也可以使用虚拟自定义验证器,将要滚动到的验证器设置为无效,然后执行
DummyCustomValidator.SetFocusOnError = true;
在我的例子中,我实际上是在一个长的垂直表单上使用带有异步回发和多个以编程方式显示/隐藏的面板的页面验证程序。由于某些字段只有在MyLogicalParent.Visible=true时才是必需的,并且如果在其他控件中给出了特定的答案,例如在复选框列表中选择“其他”时文本框上的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);
}
$(文档).ready(函数(){
var windowHeight=$(文档)[0]。documentElement.clientHeight;/*这是可查看浏览器区域的高度*/
var scrolledPosition=$(窗口)[0]。scrollY;/*这是窗口当前滚动到的像素数*/
var scroll=windowHeight+scrolledPosition;/*这应该与$(window.scrollTop()相同*/
/*如果滚动量+窗口高度小于或等于页面总高度(超过可查看的客户端窗口)*/
if($(window).scrollTop()+GetWindowsSize()[1]否。链接位于屏幕顶部。我想滚动到屏幕底部。当我回发时,它会短暂地执行此操作,因为我正在调用焦点()方法,但由于某种原因,它将向右滚动回到顶部。使用客户端脚本设置焦点。这也将负责滚动到控件。似乎也不起作用。好像我的页面上有什么东西导致它每次滚动到顶部。无法理解。是否可以添加锚定回发时标记到我的URL?asp.net web窗体中的滚动控件已损坏且无法工作。MaintainScrollPositionOnPostback是此有缺陷系统的一部分。您需要在客户端设置滚动,延迟足够长,以避免争用情况……或覆盖Microsoft的ScriptResource代码。我最终决定覆盖他们的WebForm_自动聚焦功能是使页面不会跳转的唯一方法。对页面的不同部分使用id属性(锚定标记)怎么样?您可以动态填充响应。在PostBack后重定向(“YourPageWithAnchortAgreference”)只使用UpdatePanel,我非常讨厌它们:(它对我不起作用,请看下面的ClientScript.RegisterStartupScript(..)解决方案,它对我起作用是的,Page.MaintainScrollPositionOnPostBack应该做到这一点…但它没有。@Dismissile我认为这应该被标记为答案。您不必从头重新加载页面(因此,代码只能在某些回发事件发生时应用),加上被接受的答案没有被使用,并且被声明为与要求的答案完全相反。这对我来说是有效的,设置Page.maintaintScrollPositionOnPostBack=false;在特定的情况下(因为我的页面通常设置为true)
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);
}
}
DummyCustomValidator.SetFocusOnError = true;
<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);
}