jquery need alternative to focusout()

こ雲淡風輕ζ 提交于 2019-11-27 20:15:15

Well, what might work would be to bind a "focus" handler to everything, and you know when you're not in the <div> when you get a "focus" event elsewhere.

$('body').live('focus', (function() {
  var inDiv = false;
  return function(e) {
    if ($(this).closest('#theDiv').length)
      inDiv = true;
    else {
      if (inDiv)
        alert("just lost focus!");
      inDiv = false;
    }
  };
 });

Taking Pointy's answer and going a little further with it.

creating a (simple) focuslost event plugin

(function($) {
    // will store the last focus chain
    var currentFocusChain = $();
    // stores a reference to any DOM objects we want to watch focus for
    var focusWatch = [];

    function checkFocus() {
        var newFocusChain = $(":focus").parents().andSelf();
        // elements in the old focus chain that aren't in the new focus chain...
        var lostFocus = currentFocusChain.not(newFocusChain.get());
        lostFocus.each(function() {
            if ($.inArray(this, focusWatch) != -1) {
                $(this).trigger('focuslost');
            }
        });
        currentFocusChain = newFocusChain;
    }
    // bind to the focus/blur event on all elements:
    $("*").live('focus blur', function(e) { 
        // wait until the next free loop to process focus change
        // when 'blur' is fired, focus will be unset
        setTimeout(checkFocus, 0);
    });

    $.fn.focuslost = function(fn) {
        return this.each(function() {
            // tell the live handler we are watching this event
            if ($.inArray(this, focusWatch) == -1) focusWatch.push(this);
            $(this).bind('focuslost', fn);
        });
    };
})(jQuery);

Example Use

$("div").focuslost(function() {
  $(this).append("<div>Lost Focus!</div>");
});

jsfiddle demo

Another plugin to look at is Ben Alman's Outside Events plugin. It allows you to detect when any of the following events are triggered on anything outside of a specific element and its children: clickoutside, dblclickoutside, focusoutside, bluroutside, mousemoveoutside, mousedownoutside, mouseupoutside, mouseoveroutside, mouseoutoutside, keydownoutside, keypressoutside, keyupoutside, changeoutside, selectoutside, submitoutside.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!