这个问题是通过Stack Overflow 解决的, 下面就是我的提问

editor.onmouseup = editclick;
editor.onkeydown=editinput;
function editclick(e) {
  info.innerHTML += '<br>' + document.activeElement.textContent
}
function editinput(e) {
  info.innerHTML += '<br>' + document.activeElement.textContent
}
<div id="editor" contenteditable="true" class="" tabIndex="1">
  <span>diyige span</span> saosuoasueousameli
</div>
<div id="info"></div>

when i click/keyin on the <span>deerge span</span>, the info will show all editor div. so how can i show only <span>deerge span</span> ?

方法一

js: 使用event.textcontext

editor.onmouseup = editclick;
editor.onkeypress = editKey;

function editclick(e) {
  info.innerHTML += '<br>' + e.target.textContent
}

function editKey(e) {
  info.innerHTML += '<br>' + e.target.textContent
}

针对键盘事件做的html hack

<div id="editor" contenteditable="true" class="" tabIndex="0">
  <span contenteditable="false">
    <span contenteditable="true">contenteditable span</span>
  </span><br/>
  contenteditable div content comes here. contenteditable div content comes here.
</div>
<div id="info"></div>
方法二:

使用range/selection api

editor.onmouseup = editclick;
editor.onkeydown=editinput;
function editclick(e) {
  let focus_elem = getElemAtCursor();
  info.innerHTML += '<br>' + focus_elem.textContent;
}
function editinput(e) {
  const focus_elem = getElemAtCursor();
  info.innerHTML += '<br>' + focus_elem.textContent;
}

function getElemAtCursor() {
 const elem = getSelection().getRangeAt(0).commonAncestorContainer;
 return elem.nodeType === 1 ? elem : elem.parentNode;
}

原文链接: https://stackoverflow.com/questions/61176312/document-activeelement-can-not-get-target-element