Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
821 views
in Technique[技术] by (71.8m points)

asp.net - Maintain scroll position of a div within a page on postback

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.

<div id="div1" style="overflow: auto; height: 100%;">
.....
</div>

When I scoll down in the div and click on any of the link buttons, the page reload loses the scroll position inside the div and takes me to the top of the div. Is there any way to prevent that?

Note that this is for a div inside the page. Page.MaintainScrollPositionOnPostBack() does not work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Jeff S mentioned one way to handle this situation is using javascript to track the scroll position of the div and each time the page loads reset the scroll position to its previous value.

Here's some sample code:

<html>
<body onload="javascript:document.getElementById('div1').scrollTop = document.getElementById('scroll').value;">
    <form id="form1" runat="server">
    <input type="hidden" id="scroll" runat="server" />
    <div id="div1" style="overflow: auto; height: 100px;" onscroll="javascript:document.getElementById('scroll').value = this.scrollTop">
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        <asp:LinkButton ID="LinkButton1" runat="server" Text="test2"></asp:LinkButton>
    </div>
    <asp:LinkButton ID="LinkButton2" runat="server" Text="test1"></asp:LinkButton>
    </form>
</body>
</html>

In practice I wouldn't put the javascript directly in the elements but its just an example. You could also store the scroll position in a cookie instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...