Find if a textbox is currently selected

后端 未结 5 1143
栀梦
栀梦 2021-01-12 11:08

How would I find if a textbox (or textarea) currently is in focus? I don\'t care to know which one it is, I just need to know if one is in focus (has the cursor in it). How

相关标签:
5条回答
  • 2021-01-12 11:21

    Extending the accepted answer by a check for editable HTMLDivElements:

    if (document.activeElement.nodeName == 'TEXTAREA'
        || document.activeElement.nodeName == 'INPUT'
        || (document.activeElement.nodeName == 'DIV'
            && document.activeElement.isContentEditable)) {
        // …
    }
    
    0 讨论(0)
  • 2021-01-12 11:22
    $('#target').focus(function() {
      alert('Handler for .focus() called.');
    });
    

    Also Try:

    alert($("*:focus").attr("id"));
    

    http://jsfiddle.net/4KVvV/

    0 讨论(0)
  • 2021-01-12 11:29
    $('#yourTextAreaID:focus'); 
    

    would not work. :) But

    $('#yourTextAreaID').focus(function(){
        // do something
    });
    

    would excecute the //do something code when the element receives focus.

    0 讨论(0)
  • 2021-01-12 11:36

    Since you have found document.activeElement, you can check its nodeName.

    if (document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT') {
        // ....
    }
    

    Something like that.

    0 讨论(0)
  • 2021-01-12 11:36

    Ok, just figured it out. Here's what I did:

    function checkFocus() {
    
      if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {
    
      //Something's selected
    
      return true;
    
     }
    
    }
    
    0 讨论(0)
提交回复
热议问题