jQuery - 检测用户单击输入类型文本字段的OUT

AnA*_*ice 27 jquery

我想检测用户何时单击输入类型文本字段的OUT,而不是.

这就是我所拥有的,但是两个事件都在内部点击(焦点):

<input id="title" val="hello" />

$("#title").focusout(function() {
    console.log('inside');
}).blur(function() {
    console.log('outside');
});
Run Code Online (Sandbox Code Playgroud)

hun*_*ter 60

你可以绑定你focusblur事件,如下所示:

<input id="title" val="hello" type="text" />

$("#title").focus(function() {
    console.log('in');
}).blur(function() {
    console.log('out');
});
Run Code Online (Sandbox Code Playgroud)

focusout没有必要,因为它适用于儿童元素的事件冒泡:http://api.jquery.com/focusout/


jAn*_*ndy 13

你可以写一个小插件,比如

(function($){
  $.fn.outside = function(ename, cb){
      return this.each(function(){
          var $this = $(this),
              self = this;

          $(document).bind(ename, function tempo(e){
              if(e.target !== self && !$.contains(self, e.target)){
                  cb.apply(self, [e]);
                  if(!self.parentNode) $(document.body).unbind(ename, tempo);
              }
          });
      });
  };
}(jQuery));
Run Code Online (Sandbox Code Playgroud)

..并使用它像:

$('#title').outside('click', function(e) {
    console.log('outside');
});
Run Code Online (Sandbox Code Playgroud)

示例:http://www.jsfiddle.net/tGnun/