Вот как справиться с потерей позиции прокрутки при использовании тегов <DIV>
.
Добавьте следующую функцию, чтобы она была доступна для всех ваших страниц, где вы хотите управлять позициями прокрутки.
protected void RetainScroll(string ids, bool isPostBack)
{
if (String.IsNullOrEmpty(ids))
return;
//register js method on page load event to set the previous scroll position.
ScriptManager.RegisterStartupScript(this, Page.GetType(), "scroll", "javascript:RSSetScroll();", true);
if (isPostBack)
{
//just register startup call and return
return;
}
string[] allDivs = ids.Split(new char[] { ',' });
if (allDivs.Length <= 0)
return;
//construct the js functions
StringBuilder setScroll = new StringBuilder(512);
StringBuilder onScroll = new StringBuilder(512);
setScroll.Append("function RSSetScroll(){");
onScroll.Append("function RSOnScroll(tdiv, hvar) {");
foreach (string div in allDivs)
{
string hVar = div + "__h";
Page.RegisterHiddenField(hVar, "0:0");
setScroll.Append("if(document.getElementById('" + div + "')!=null) document.getElementById('" + div + "').scrollTop = 0;");
setScroll.Append("if(document.getElementById('" + div + "')!=null) document.getElementById('" + div + "').scrollLeft = 0;");
setScroll.Append("if(document.getElementById('" + div + "')!=null) document.getElementById('" + div + "').scrollTop = document.getElementById('" + hVar + "').value.split(':',2)[0];");
setScroll.Append("if(document.getElementById('" + div + "')!=null) document.getElementById('" + div + "').scrollLeft = document.getElementById('" + hVar + "').value.split(':',2)[1];");
Control ctrl = Page.FindControl(div);
if (ctrl != null)
if (ctrl.GetType() == typeof(HtmlGenericControl))
{
((HtmlGenericControl)(ctrl)).Attributes.Add("onscroll", "javascript:RSOnScroll(this,'" + hVar + "')");
}
}
setScroll.Append("}");
onScroll.Append("document.getElementById(hvar).value = tdiv.scrollTop +':'+tdiv.scrollLeft;");
onScroll.Append("}");
//insert js functions to page
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "RC", setScroll.ToString() + onScroll.ToString(), true);
}
Эта функция вставит скрытую переменную, в которой позиции прокрутки будут сохранены на задних сторонах, для различных тегов DIV.Когда страница отображается, соответствующие позиции прокрутки будут возвращены в теги DIV.Я использую эту технику для установки позиций прокрутки.
Вот как вы используете эту функцию в своем коде позади файла:
protected void Page_Load(object sender, EventArgs e)
{
RetainScroll("divClientID1,divClientID2,divClientID3", IsPostBack);
}
Не беспокойтесь о состоянии IsPostBack
, онообрабатывается внутри самого метода.Приведенный выше пример вызова сохранит позиции прокрутки для divClientID1
, divClientID2
и divClientID3
во время обратной передачи на страницу.