Maintain scroll position of a div within a page on postback

后端 未结 5 1799
无人共我
无人共我 2020-12-14 22:36

I have a div within an aspx page with overflow set to auto. The contents of the div are dynamically created and consists of a list of link buttons.

5条回答
  •  無奈伤痛
    2020-12-14 23:29

    using System;
    using System.ComponentModel;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    [ParseChildren(true, "Content")]
    public class ScrollSaverPanel: WebControl
    {
        [TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ITemplate Content { get; set; }
    
        private HiddenField HiddenField { get; set; }
    
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
    
        protected override void OnInit(EventArgs e)
        {
            HiddenField = new HiddenField();
    
            var metaContainer = new WebControl(HtmlTextWriterTag.Div);
            metaContainer.Controls.Add(HiddenField);
            metaContainer.Style.Add(HtmlTextWriterStyle.Display, "none");
    
            Controls.Add(metaContainer);
    
            var contentContainer = new WebControl(HtmlTextWriterTag.Div);
            Controls.Add(contentContainer);
    
            Content.InstantiateIn(contentContainer);
    
            this.Style.Add(HtmlTextWriterStyle.Overflow, "auto");
            this.Attributes.Add("onscroll", string.Format("javascript:document.getElementById('{0}').value = this.scrollTop;", HiddenField.ClientID));
    
            base.OnInit(e);
        }
    
        protected override void OnPreRender(EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "setscroll", string.Format("javascript:document.getElementById('{0}').scrollTop = '{1}';", this.ClientID, HiddenField.Value), true);
            base.OnPreRender(e);
        }
    }
    

    Usage:

    
        
            
        
    
    

    Since some people don't want to use an Updatepanel for the sole purpose of saving scroll position... :)

提交回复
热议问题