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>
?
使用e.target.textContent
对于鼠标事件,这是可行的,但对于嵌套contenteditable
元素的键盘事件,则需要应用一个小技巧:
将contenteditable="true"
设置为span
,然后用另一个具有span
的contenteditable="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>
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;
}