document.activeElement无法获取目标元素

问题描述 投票:1回答:2

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>

当我单击/键入<span>deerge span</span>时,该信息将显示所有编辑器div。所以我怎么只显示<span>deerge span</span>

javascript contenteditable
2个回答
0
投票

使用e.target.textContent

对于鼠标事件,这是可行的,但对于嵌套contenteditable元素的键盘事件,则需要应用一个小技巧:

contenteditable="true"设置为span,然后用另一个具有spancontenteditable="false"包装

检查下面的代码:

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

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

function editKey(e) {
  info.innerHTML += '<br>' + e.target.textContent
}
body {
  background: #fff;
}
<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>

0
投票

document.activeElement将返回当前具有focus的元素。在您的情况下,吸引焦点的一个元素是容器

。您必须在元素上设置tabindex属性以使其可聚焦,但是在您的 contenteditable区域中这样做并不实用。

相反,您可能需要Range.commonAncestorContainer元素,它将是当前选择实际上所在的元素,因此,在您的情况下,就是光标所在的元素。

editor.onmouseup = editclick;
editor.onkeydown=editinput;
function editclick(e) {
  const focus_elem = getSelection().getRangeAt(0).commonAncestorContainer;
  info.innerHTML += '<br>' + focus_elem.textContent;
}
function editinput(e) {
  const focus_elem = getSelection().getRangeAt(0).commonAncestorContainer;
  info.innerHTML += '<br>' + focus_elem.textContent;
}
<div id="editor" contenteditable="true" class="">
  <span>diyige span</span> saosuoasueousameli
</div>
<div id="info"></div>

也许您甚至更喜欢Range.startContainer,它将返回光标所在的Node。

Range.startContainer
editor.onmouseup = editclick;
editor.onkeydown=editinput;
function editclick(e) {
  const focus_elem = getSelection().getRangeAt(0).startContainer;
  console.log(focus_elem);
  info.innerHTML += '<br>' + focus_elem.textContent;
}
function editinput(e) {
  const focus_elem = getSelection().getRangeAt(0).startContainer;
  info.innerHTML += '<br>' + focus_elem.textContent;
}
© www.soinside.com 2019 - 2024. All rights reserved.