焦点不是由点击触发的

时间:2013-06-16 06:26:29

标签: javascript jquery

如何在聚焦输入但是聚焦事件不是来自点击时触发动作?

$('#input').focus(function(){
  if(not come from click)
  {
    alert('Holla!');
  }
});

3 个答案:

答案 0 :(得分:5)

要介绍来自键盘的“焦点”事件和来自鼠标的事件,您可以跟踪鼠标事件。

首先,要了解单击输入或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
  • 专注
  • mouseup
  • 点击
  • 模糊

但是如果我们进入和退出输入,我们将在控制台中看到:

  • 焦点
  • 模糊

因此,如果我们跟踪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/

答案 1 :(得分:1)

使用keyup

 $('#input').keyup(function(){
    alert('Called only when the focus is on element through keypress');
 });

答案 2 :(得分:1)

function ren(){

    alert('Holla!');

}
$('input').focus(ren);
$('input').mousedown(function(){      
$('input').off('focus',ren);  
});
$('input').mouseup(function(){      
$('input').on('focus',ren);  
});

在点击时不要检查对焦功能而是取消对焦功能

Demonstration

相关问题