我在带有更新面板的页面中有四个控件。最初,鼠标焦点设置为第一个控件。当我将页面部分回发到服务器时,焦点自动移至我已制表到的控件中的最后一个焦点控件中的第一个控件。有什么办法可以保持最后的焦点?
最佳答案
看看Restoring Lost Focus in the Update Panel with Auto Post-Back Controls:
The basic idea behind the solution is to save the ID of the control with input focus before the update panel is updated and set input focus back to that control after the update panel is updated.
I come with the following JavaScript which restores the lost focus in the update panel.
var lastFocusedControlId = ""; function focusHandler(e) { document.activeElement = e.originalTarget; } function appInit() { if (typeof(window.addEventListener) !== "undefined") { window.addEventListener("focus", focusHandler, true); } Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler); Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler); } function pageLoadingHandler(sender, args) { lastFocusedControlId = typeof(document.activeElement) === "undefined" ? "" : document.activeElement.id; } function focusControl(targetControl) { if (Sys.Browser.agent === Sys.Browser.InternetExplorer) { var focusTarget = targetControl; if (focusTarget && (typeof(focusTarget.contentEditable) !== "undefined")) { oldContentEditableSetting = focusTarget.contentEditable; focusTarget.contentEditable = false; } else { focusTarget = null; } targetControl.focus(); if (focusTarget) { focusTarget.contentEditable = oldContentEditableSetting; } } else { targetControl.focus(); } } function pageLoadedHandler(sender, args) { if (typeof(lastFocusedControlId) !== "undefined" && lastFocusedControlId != "") { var newFocused = $get(lastFocusedControlId); if (newFocused) { focusControl(newFocused); } } } Sys.Application.add_init(appInit);
关于asp.net - 页面部分回发后如何在UpdatePanel中保持焦点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2703079/