See if ContentEditable div has focus

后端 未结 4 2025
独厮守ぢ
独厮守ぢ 2021-02-14 07:25

I\'m attempting to check whether or not a contenteditable div has focus, but I\'m having some trouble. Here\'s my code so far:

if ($(\"#journal-content:focus\")         


        
相关标签:
4条回答
  • 2021-02-14 07:29

    What about this?:

    if (document.activeElement.isContentEditable) {
    ...
    }
    

    I don't know how well browser support for this is but at least Chrome and Firefox support it.

    0 讨论(0)
  • 2021-02-14 07:35

    You can try this

    if ($("#journal-content").is(":focus")) {
    ...
    

    Maybe if you'll tell us what are you trying to achieve we'll be of a more help. Meanwhile, you can have a read here: http://api.jquery.com/focus-selector/.

    0 讨论(0)
  • 2021-02-14 07:43

    Try:

    if ($("#journal-content").is(":focus")) {
        alert("Has Focus");
    } else {
        alert("Doesn't Have Focus");
    }
    

    Or:

    window.contenteditable_focused = false;
    
    $("#journal-content").focus(function() {
        //alert("Has Focus");
        contenteditable_focused = true;
    });
    $("#journal-content").blur(function() {
        //alert("Doesn't Have Focus");        
        contenteditable_focused = false;
    });
    

    Check for contenteditable_focused before executing your script.

    Or:

    if ($( document.activeElement ).is("#journal-content")) {
        alert("Has Focus");
    } else {
        alert("Doesn't Have Focus");
    }
    
    0 讨论(0)
  • 2021-02-14 07:46

    For pure JavaScript when you have multiple contenteditable elements:

    Check document.activeElement.id or document.activeElement.isContentEditable.

    Example:

    function isFocused() {
      if (document.activeElement.id === "journal-content") {
        alert("Focused!");
      } else {
        alert("Not focused :(");
      }
    }
    #journal-content {
      background-color: #eee;
    }
    #not-journal-content {
      background-color: #ccc;
    }
    <div id="journal-content" contenteditable="true" onclick="isFocused()">Journal Content</div>
    <div id="not-journal-content" contenteditable="true" onclick="isFocused()">Not Journal Content</div>

    0 讨论(0)
提交回复
热议问题