我目前正在尝试使用 contenteditable div 制作一个编辑器,但遇到一个问题,在开始时单击 child-2 中的退格键将导致合并 child- 1 和 child-2 在一起,这违背了它自己的目的。
我正在使用以下函数查找当前插入符位置:
caret: function() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) return sel.getRangeAt(0).startOffset;
}
return null;
}
这一直工作得很好,但是为了解决合并问题,我需要找出当前选择了哪个元素,并将该数据与插入符号位置一起使用,以使用 event.preventDefault()
并停止潜在的合并。
这是我正在使用和谈论的框架:
<div id="parent" contenteditable="true">
<div id="child-1">
One
</div>
<div id="child-2">
Two
</div>
<div id="child-3">
Three
</div>
</div>
为了查找所选元素,我尝试过以下操作:
console.log(document.activeElement);
看看这是否会打印出所选子元素的ID,尽管这会将整个父元素输出到控制台,而不仅仅是 ID。
最佳答案
使用Event Delegation轻松找到单击的节点。还可以添加其他事件,例如按键和鼠标。
详细信息在演示中评论
演示
// Refernce the parent of all of the target nodes
var parent = document.getElementById('parent');
// Register the click event to #parent
parent.addEventListener('click', idNode);
// This is the callback that is invoked on each click
function idNode(e) {
/* If the node clicked (e.target) is not the
|| the registered event listener
|| (e.currentTarget = #parent)
*/
if (e.target !== e.currentTarget) {
// Get the #id of clicked node
var ID = e.target.id;
// Reference e.target by its #id
var child = document.getElementById(ID);
}
// Log the #id of each e.target at every click
console.log('The caret is located at ' + ID);
// Return the e.target as a DOM node when needed
return child;
}
<div id="parent" contenteditable="true">
<div id="child-1">
One
</div>
<div id="child-2">
Two
</div>
<div id="child-3">
Three
</div>
</div>
关于javascript - 获取光标插入符所在的选定内容可编辑元素的子元素的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46436973/