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

时间:2010-04-24 03:16:59

标签: asp.net ajax updatepanel

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

2 个答案:

答案 0 :(得分:10)

看看Restoring Lost Focus in the Update Panel with Auto Post-Back Controls

  

解决方案背后的基本思想是保存控件的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);

答案 1 :(得分:3)

我发现这更优雅:

    (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);
    });
})();