asp.net - 页面部分回发后如何在UpdatePanel中保持焦点位置

标签 asp.net ajax updatepanel

我在带有更新面板的页面中有四个控件。最初,鼠标焦点设置为第一个控件。当我将页面部分回发到服务器时,焦点自动移至我已制表到的控件中的最后一个焦点控件中的第一个控件。有什么办法可以保持最后的焦点?

最佳答案

看看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/

相关文章:

c# - 如何更改 Blazor WASM 身份页面导航栏中的标题/品牌?

javascript - ASP NET 自定义验证器错误消息未显示

ajax - 当 ajax 目标为 localhost 时,IE 10 和 11 中的访问被拒绝

javascript - AJAX:无法将 javascript 变量传递给 PHP 脚本中的 SQL 查询

c# - ASP.NET 中带有 UpdatePanel 的 CodeMirror

asp.net - 我可以将 HTML5 WebSockets 用于通常使用 AJAX 完成的任务吗?

javascript - AC_FL_RunContent 在 UpdatePanel 回发后不工作

基于 Asp.Net MVC 操作的自定义授权

c# - asp.net 工具提示对于里面的文本来说显得很大

ajax - Node、Express、Ajax 和 Jade 示例