我们常将内容放在Panel中,例如文章,GridView控件等....。当内容超出Panel的高、宽时,可能就需要滚动条来进行控制。 当点击页面中按钮产生PostBack时,滚动条总是会回到最上面的位置,我们现在要解决的主要就是这个问题。
- private void HandlePanelScrolBar()
- ...{
- //定义两个HiddenField,分别纪录Panel的ScrollBar的X与Y位置
- HiddenField HF_ScrollPosX = new HiddenField();
- HiddenField HF_ScrollPosY = new HiddenField();
- HF_ScrollPosX.ID = "ScrollPosX";
- HF_ScrollPosY.ID = "ScrollPosY";
- form1.Controls.Add(HF_ScrollPosX);
- form1.Controls.Add(HF_ScrollPosY);
- //生成JS:将Panel的ScrollBar的X,Y位置设置给两个HiddenField
- string script;
- script = "window.document.getElementById('" + HF_ScrollPosX.ClientID + "').value = "
- + "window.document.getElementById('" + P_Container.ClientID + "').scrollLeft;"
- + "window.document.getElementById('" + HF_ScrollPosY.ClientID + "').value = "
- + "window.document.getElementById('" + P_Container.ClientID + "').scrollTop;";
- this.ClientScript.RegisterOnSubmitStatement(this.GetType(), "SavePanelScroll", script);
- if (IsPostBack) //如果是PostBack,将保存在HiddenField的ScrollBar的X,Y值重设回给Panel的ScrollBar
- ...{
- script = "window.document.getElementById('" + P_Container.ClientID + "').scrollLeft = "
- + "window.document.getElementById('" + HF_ScrollPosX.ClientID + "').value;"
- + "window.document.getElementById('" + P_Container.ClientID + "').scrollTop = "
- + "window.document.getElementById('" + HF_ScrollPosY.ClientID + "').value;";
- this.ClientScript.RegisterStartupScript(this.GetType(), "SetPanelScroll", script, true);
- }
- }
代码中的P_Container为Panel的名字