[英]Maintain scroll position on postback in a ListView with asp.net and Master Pages
[英]ASP.net Postback - Scroll to Specific Position
我有一個 ASP.net WebForms 頁面,在屏幕頂部有很多內容。 它有一個鏈接按鈕,可以發回頁面並顯示頁面的另一部分。 當頁面刷新時,我想設置焦點並向下滾動到頁面的這一部分。
我試着做
txtField.Focus()
在我后面的代碼中,它會設置焦點並嘗試在那里滾動,但隨后會滾動回頂部。 焦點仍然在我的文本框上,但屏幕的 position 位於最頂部。 鏈接位於導致回發的屏幕頂部。 我想滾動到屏幕的最底部。 它會簡短地執行此操作,然后直接滾動回頂部。
我試過設置
Page.MaintainScrollPositionOnPostback = false;
但這似乎也無濟於事。
有什么方法可以強制它到 go 到特定的 position? 當我使用按鈕或鏈接按鈕回發時,是否可以向 URL 添加錨標記?
Page.MaintainScrollPositionOnPostBack = true;
應該帶你回到屏幕上相同的 position,但你可以使用 AJAX,或者你可以使用SetFocus()
在回發后專注於特定控件:
如果您有該位置的錨點,則可以使用以下代碼:
Page.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自動滾動
嘗試這個
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);
}
}
Page.MaintainScrollPositionOnPostback = true
似乎工作得很好。
我已經嘗試過Matthieu Charbonnier 的回答,但除非我添加了,否則它不起作用
" window.scrollTo = function () { };"
我創建了一個輔助方法,它在 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>
在 *.aspx 頁面上。 並在 *.aspx.cs 頁面上單擊按鈕。
Page.SetFocus(mvAriza.ClientID);
它工作得很好。
這會自動滾動到 asp.net 控件中的所需 Div 這是 Function 從你想要的地方調用它,還下載 Java 腳本文件
OnClientClick="返回滾動網格()"
function scrollGrid1() { $('html,body').animate ( { scrollTop: $('#Div1').offset().top }, 'slow' ) }
雖然不適合您的情況,但也可以使用虛擬自定義驗證器,將您要滾動的驗證器設置為無效,然后執行
DummyCustomValidator.SetFocusOnError = true;
就我而言,我實際上是在使用帶有異步回發和多個以編程方式顯示/隱藏在長垂直表單上的面板的頁面驗證器。 由於僅當 MyLogicalParent.Visible = true 並且在其他控件中給出特定答案時才需要某些字段,例如在 CheckBoxList 中選擇“Other”時 TextBox 上的 RequiredFieldValidator,所以我有很多邏輯來處理頁面驗證。 在所有常規方法中設置滾動位置都很痛苦。
當異步回發改變頁面的垂直尺寸時,我還使用 RegisterStartupScript 來處理維護當前滾動 position。
<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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.