jQuery lose focus event

前端 未结 5 1426
小鲜肉
小鲜肉 2020-12-22 17:15

I\'m trying to show up a container if a input field gets the focus and - that\'s the actual problem - hide the container if focus is lost. Is there an opposite event for jQu

相关标签:
5条回答
  • 2020-12-22 17:24

    blur event: when the element loses focus.

    focusout event: when the element, or any element inside of it, loses focus.

    As there is nothing inside the filter element, both blur and focusout will work in this case.

    $(function() {
      $('#filter').blur(function() {
        $('#options').hide();
      });
    })
    

    jsfiddle with blur: http://jsfiddle.net/yznhb8pc/

    $(function() {
      $('#filter').focusout(function() {
        $('#options').hide();
      });
    })
    

    jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/

    0 讨论(0)
  • 2020-12-22 17:26

    Use "blur": http://docs.jquery.com/Events/blur#fn

    0 讨论(0)
  • 2020-12-22 17:33

    If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?

    So you can setup variables like so:

    var $coolOptions= $("<div id='options'></div>").text("Some cool options");
    

    and then append (or prepend) on focus

    $("input[name='input_name']").focus(function() {
        $(this).append($coolOptions);
    });
    

    and then remove when the focus ends

    $("input[name='input_name']").focusout(function() {
        $('#options').remove();
    });
    
    0 讨论(0)
  • 2020-12-22 17:34

    Use blur event to call your function when element loses focus :

    $('#filter').blur(function() {
      $('#options').hide();
    });
    
    0 讨论(0)
  • 2020-12-22 17:50

    Like this:

    $(selector).focusout(function () {
        //Your Code
    });
    
    0 讨论(0)
提交回复
热议问题