聚焦输入但焦点事件不是来自点击时如何触发动作?
$('#input').focus(function(){
  if(not come from click)
  {
    alert('Holla!');
  }
});
聚焦输入但焦点事件不是来自点击时如何触发动作?
$('#input').focus(function(){
  if(not come from click)
  {
    alert('Holla!');
  }
});
要区分来自键盘的“焦点”事件和来自鼠标的“焦点”事件,您可以跟踪鼠标事件。
首先,要了解单击输入或 Tab 进入输入时发生的事件顺序,请查看以下 jsfiddle:http: //jsfiddle.net/orlenko/fyFkk/
在其中,我们将记录 mousedown、mouseup、click、focus 和 blur 事件。\
<input type="text" id="zero"/>
<input type="text" id="one"/>
JavaScript:
$(function() {
    var one = $('#one');
    one.mousedown(function() {
       console.log('mousedown');
    });
    one.mouseup(function() {
       console.log('mouseup');
    });
    one.click(function() {
       console.log('click');
    });
    one.focus(function() {
       console.log('focus');
    });
    one.blur(function() {
       console.log('blur');
    });
});
如果我们简单地单击输入,然后单击另一个控件,我们将得到以下信息:
但是如果我们进入和退出输入,我们将在控制台中看到:
因此,如果我们跟踪 mousedown 和 blur 事件,我们可以区分基于键盘的焦点和基于鼠标的焦点。例如:
$(function() {
    var one = $('#one');
    one.mousedown(function() {
       console.log('mousedown');
        $(this).data('mousedown', true);
    });
    one.mouseup(function() {
       console.log('mouseup');
    });
    one.click(function() {
       console.log('click');
    });
    one.focus(function() {
        if ($(this).data('mousedown')) {
            console.log('You clicked it!');
        } else {
            console.log('You tabbed it!');
        }
    });
    one.blur(function() {
       console.log('blur');
       $(this).data('mousedown', false);
    });
});
这个例子的小提琴:http: //jsfiddle.net/orlenko/cwRAw/
利用keyup
 $('#input').keyup(function(){
    alert('Called only when the focus is on element through keypress');
 });
function ren(){
    alert('Holla!');
}
$('input').focus(ren);
$('input').mousedown(function(){      
$('input').off('focus',ren);  
});
$('input').mouseup(function(){      
$('input').on('focus',ren);  
});
在点击时不要签入焦点功能,而是删除焦点功能