[英]Get ID of selected contenteditable element's child where cursor caret is located
我目前正在尝试使用 contenteditable div 制作编辑器,但我遇到了一个问题,即在开始时单击child-2中的退格键会导致child-1和child-2合并在一起,这违背了它自己的目的。
我正在使用 function 找到当前的插入符号 position:
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。
使用事件委托可以轻松找到单击的节点。 也可以添加其他事件,例如按键和鼠标。
演示中有详细评论
// 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>
您可以将tabindex="0"
应用于子元素,从而使它们可聚焦,这将在使用document.activeElement
时选择子元素(否则,始终是具有焦点的父元素):
console.log(document.activeElement);
<div id="parent" contenteditable="true"> <div id="child-1" tabindex="0"> One </div> <div id="child-2" tabindex="0"> Two </div> <div id="child-3" tabindex="0"> Three </div> </div>
发表评论后:我正在添加此片段的屏幕截图:单击单词“ Two”:您可以看到该行周围的虚线边框指示焦点状态:
通过使用document.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.parentNode.parentNode.id
您可以获得插入符号的父元素的 id。
例子
function getParentId() { var caret = document.getSelection().getRangeAt(0); var caretParent = caret.commonAncestorContainer.parentNode; console.log(caretParent.id); }
<div id="parent" contenteditable="true"> <div id="child-1" tabindex="0"> One </div> <div id="child-2" tabindex="0"> Two </div> <div id="child-3" tabindex="0"> Three </div> </div> <button onclick="getParentId()">Get Id</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.