火狐下,怎么让文本框获取焦点?focus方法不行,IE下出现诡异现象


代码如下:


 <input type="text" placeholder="输入昵称" required name="username" id="username">
<input type="email" placeholder="输入您的邮箱" required name="useremail" id="useremail">

检测代码


 // 检测昵称
    $("#username").blur(function(){
        if($(this).val()===''){
            $(this).css({
                backgroundColor:"#FFF",
                borderColor:"#FD8F8F"
            }).focus();
        }else{
            $(this).css({
                backgroundColor:"#EDEAEA",
                borderColor:"#7ED0F2"
            }).next().show();
        }
    });
    // 检测邮箱
    $("#useremail").blur(function(){
        if($(this).val()===''){
            $(this).css({
                backgroundColor:"#FFF",
                borderColor:"#FD8F8F"
            }).focus();
        }else{
            $(this).css({
                backgroundColor:"#EDEAEA",
                borderColor:"#7ED0F2"
            }).next().show();
        }
    });

当username文本框是空,失去焦点时,username文本框并不能多获取焦点,鼠标依然能移动到useremail框(在谷歌表现正常,IE下会有诡异的事情发生),请问是什么原因,如何处理?

在线运行: 问题的demo 如果对于描述不清楚,可以再谷歌、IE和火狐下分别测试一下。

input 焦点 JavaScript 火狐

农妇山泉有点田 9 years, 9 months ago

火狐的事件触发细节有些不同,所以导致 blur 发生时, focus() 已经执行,接下来由于 focus 了其他元素,导致已经获得焦点的 input[name="username"] 失焦。具体的执行顺序题主可以通过断点或者 window.alert 跟踪。

以下是我做的改动,通过 setTimtout(cb,0) 使得 focus 插入到上述一系列操作之后。问题就可以解决。


 javascript


 $("#username").blur(function(){
  var $this=$(this);
  if($this.val()===''){
    setTimeout(function(){
      $this.css({
        backgroundColor:"#FFF",
        borderColor:"#FD8F8F"
      }).focus();
    },0);   
  }
});

http://jsfiddle.net/nta10x3e/1/

popopjk answered 9 years, 9 months ago

Your Answer