在C#中检测聚焦控制

时间:2012-01-25 12:18:50

标签: c# asp.net focus updatepanel

我有一个更新面板,它在页面的一部分上引起回发,并且在回发之后,具有焦点的控件(不在更新面板中)失去焦点。如何识别哪个控件具有焦点并保存该值,以便在页面重新加载时可以重新聚焦它。谢谢。

3 个答案:

答案 0 :(得分:1)

首先,我将焦点绑定在所有输入上并保留最后一个焦点控制ID。然后在UpdatePanel完成加载后,我将焦点设置为最后一个

// keep here the last focused id
var LastFocusedID = null;

function watchTheFocus()
{
  // on every input that get the focus, I grab the id and save it to global var
  $(":input").focus(function () {
     LastFocusedID = this.id;
  });   
}

var prm = Sys.WebForms.PageRequestManager.getInstance();    
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);

function InitializeRequest(sender, args) {      
}

// after the updatePanel ends I re-bind the focus, and set the focus
//  to the last one control
function EndRequest(sender, args) {
    if(LastFocusedID != null)
        $('#' + LastFocusedID).focus();        
    watchTheFocus();
}

jQuery(document).ready(function() 
{       
    watchTheFocus();
});

唯一的想法是我使用jQuery来制作它,但我在这里提出了我的想法,你可以用更多的代码用jQuery来实现它。

答案 1 :(得分:0)

您可以使用activeElementhasFocus属性向HTMLDocument对象获取使用javascript关注的元素。

所有人可能都不支持这是HTML5。

答案 2 :(得分:0)

你可以这样解决

var last_focused = null;

$(function () {

 //store last focused element.

 $("input").live("focus", function(){
   last_focused = $(this);
 });


});

//in Script manager

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);

function pageLoaded(sender, args)
{
  if(last_focused != null) 
  {
    last_focused.focus();
  }
}
相关问题