在回发时保持页面内div的滚动位置

Nik*_*hil 10 html asp.net postback scroll scroll-position

我在aspx页面中有一个div,溢出设置为auto.div的内容是动态创建的,由一系列链接按钮组成.

<div id="div1" style="overflow: auto; height: 100%;">
.....
</div>
Run Code Online (Sandbox Code Playgroud)

当我在div中按下并单击任何链接按钮时,页面重新加载会丢失div中的滚动位置并将我带到div的顶部.有什么方法可以阻止这种情况吗?

请注意,这是针对页面内的div.Page.MaintainScrollPositionOnPostBack()不起作用.

jos*_*shb 14

正如Jeff S所提到的,处理这种情况的一种方法是使用javascript来跟踪div的滚动位置,每次页面加载时将滚动位置重置为其先前的值.

这是一些示例代码:

<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>
Run Code Online (Sandbox Code Playgroud)

在实践中,我不会将javascript直接放在元素中,但它只是一个例子.您也可以将滚动位置存储在cookie中.


Ben*_*old 5

最简单的方法是将控件包装在UpdatePanel中.