页面部分回发后,如何在UpdatePanel中保持焦点位置

Dee*_*Dee 5 asp.net ajax updatepanel

我有一个带有更新面板的页面中的四个控件.最初将鼠标焦点设置为第一个控件.当我将页面部分回发到服务器时,焦点自动从最后一个聚焦控件从我已选中的控件移动到第一个控件.有没有办法保持最后的焦点?

drs*_*222 10

看看与汽车后回控制更新面板中恢复失去焦点:

该解决方案背后的基本思想是在更新更新面板之前使用输入焦点保存控件的ID,并在更新面板更新后将输入焦点设置回该控件.

我带来了以下JavaScript,它可以在更新面板中恢复丢失的焦点.

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


小智 5

我觉得这更优雅:

    (function(){
    var focusElement;
    function restoreFocus(){
        if(focusElement){
            if(focusElement.id){
                $('#'+focusElement.id).focus();
            } else {
                $(focusElement).focus();
            }
        }
    }

    $(document).ready(function () {
        $(document).on('focusin', function(objectData){
            focusElement = objectData.currentTarget.activeElement;
        });
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(restoreFocus);
    });
})();
Run Code Online (Sandbox Code Playgroud)