检测C#中的聚焦控制
本文关键字:聚焦 控制 检测 | 更新日期: 2023-09-27 18:21:27
我有一个更新面板,它导致页面的一部分回发,回发后,具有焦点的控件(不在更新面板中)失去焦点。如何识别哪个控件具有焦点并保存该值,以便在页面重新加载时重新聚焦到它。非常感谢。
首先我将焦点绑定在所有输入上,并保留最后一个焦点控件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来制作它,但我在这里提出了我的想法,你可以用更多的代码来制作它。
使用activeElement
和hasFocus
属性到HTMLDocument
对象,您可以使用javascript获取哪个元素具有焦点
由于它是HTML5,可能不是所有人都支持它。
你可以像这样解决
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();
}
}