【问题标题】:RadioButton doesn't "receive" focusRadioButton 不“接收”焦点
【发布时间】:2011-12-02 07:05:41
【问题描述】:

我拼凑了一些在 ASP.NET 中使用的代码,以防止控件失去对回发的关注,因此选项卡或单击另一个控件可以保存用户位置并返回它。

在 Page_Load 我有以下内容:

PartNum_tb.Attributes["onfocus"] = "gotFocus(this)";
Department_tb.Attributes["onfocus"] = "gotFocus(this)";
PartWeight_tb.Attributes["onfocus"] = "gotFocus(this)";
Standard_rb.Attributes.Add("onfocus","gotFocus(this)");
Special_rb.Attributes.Add("onfocus","gotFocus(this)");

if (Page.IsPostBack)
   Page.SetFocus(tabSelected.Value);

这是我的 Javascript(tabSelected 是一个隐藏字段):

<script type="text/javascript">
    function gotFocus(control) {
        document.getElementById('form1').tabSelected.value = control.id;

        if (control.type == "text") {
            if (control.createTextRange) {
                //IE  
                var FieldRange = control.createTextRange();
                FieldRange.moveStart('character', control.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }
            else {
                //Firefox and Opera  
                control.focus();
                var length = control.value.length;
                control.setSelectionRange(length, length);
            }
        }
    }
</script>

问题是当我选择或单击其中一个单选按钮时,它会将焦点返回到最后一个控件的位置,这对用户来说是不直观且令人困惑的。这样做是因为 RadioButton 永远不会获得焦点,因此光标位置不会得到更新。在广泛的 Google 搜索之后,似乎它不可能知道 RadioButton 何时获得焦点。是否有任何已知的解决方案可以解决这个问题?

【问题讨论】:

  • 澄清一下:发生这种情况的原因是因为上面两个 RadioButtons 的 Attributes.Add("onfocus") 基本上是没用的。它什么都不做,永远不会被调用。
  • 对不起,我不知道问题出在哪里,但首先想到的是尝试为您的单选按钮设置“onclick”而不是“onfocus”,其中“onclick” " 仍然会调用你的 "gotFocus()" 函数(并且你会继续为你的其他元素使用 "onfocus")。
  • 感谢您的回复。 “onclick”仅在我单击选定的单选按钮时才有效。如果我先点击一个未选中的,或者在表单中切换(这可能是用户将要执行的操作),焦点仍会跳回上一个控件。

标签: javascript asp.net focus radio-button


【解决方案1】:

解决方案可能是将keypress 事件添加到前一个字段并在无线电上使用click 事件。另外,将control.focus(); 移出if 语句:

Javascript

function changeFocus(next) {
    gotFocus(next);
}

function gotFocus(control) { 
    document.getElementById('form1').tabSelected.value = control.id; 
    control.focus();

    if (control.type == "text") { 
        if (control.createTextRange) { 
            //IE   
            var FieldRange = control.createTextRange(); 
            FieldRange.moveStart('character', control.value.length); 
            FieldRange.collapse(); 
            FieldRange.select(); 
        } 
        else { 
            //Firefox and Opera   
            var length = control.value.length; 
            control.setSelectionRange(length, length); 
        } 
    } 
} 

【讨论】:

  • 我决定走一个完全不同的方向,只是让我的控件不发回并首先导致这个问题。该解决方案感觉就像一个黑客,但我认为你是对的,这是唯一可以做到的方法。感谢您的回复。 (赏金 50 分钟)
猜你喜欢
  • 2015-04-04
  • 2019-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多