由于您正在使用UpdatePanels,因此需要连接到ASP.NET AJAX的PageRequestManager
您需要添加一个方法到endRequest事件钩子中:
在异步回发完成并且控件已经返回到浏览器之后引发。
所以您应该有如下代码:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(pageLoaded);
function pageLoaded(sender, args) {
window.scrollTo(0,0);
}
</script>
在更新请求完成后,这将强制浏览器滚动回页面顶部。
当然,您可以钩入其他事件:
beginRequest // Raised before the request is sent
initializeRequest // Raised as the request is initialised (good for cancelling)
pageLoaded // Raised once the request has returned, and content is loaded
pageLoading // Raised once the request has returned, and before content is loaded
异步回发的优点在于,页面会保持滚动高度而不需要设置MaintainScrollPosition,因为没有发生“完整页面重新加载”,但是在这种情况下您实际上需要那种效果,所以您需要手动创建它。
编辑以响应更新的问题:
好的,所以如果您只需要在某些按钮按下时重置位置,您需要执行以下操作:
首先,钩入BeginRequest而不是/也是:
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler)
这是因为在参数(args)中你可以访问到:
args.get_postBackElement().id
以下代码将告诉您启动整个事件的按钮ID-然后您可以在此处检查该值并移动页面,或者将其存储在变量中并在最终请求中查询它-请注意竞争条件等情况,其中用户在原始更新完成前单击另一个按钮。
希望这对你有所帮助-在“使用PageRequestManager事件”上有很多示例。