我正在使用Javascript构建一个简单易用的文本编辑器,基本上是一个WYSIWYG编辑器.我将使用contenteditable属性到主包装器(.wrapper).当您在其中按Enter键时,具有唯一.wrapper的新<p>元素id将附加到包装器.
我需要一种方法来获取.wrapper当前所选择的子元素(即,被聚焦或在其中具有插入符号/文本标记).
我搜索了几天没有任何结果,我尝试过使用document.elementFromPoint()但没有任何正确的结果.
使用时$(":focus"),我得到整个.wrapper而不是特定的子元素.
编辑:
示例HTML结构:
<div class="container t-wrapper" contenteditable>
</div>
Run Code Online (Sandbox Code Playgroud)
示例Javascript代码:
$(document).ready(function() {
$currentElement = $("[contenteditable]");
$(".t-wrapper").each(function() {
var id = generateIdentifier(6); // Ignore this
/* This creates the initial <p> child element, where you start typing. */
$(this).html('<p class="t-empty t-first" id="' + id + '"></p>');
$(this).on("mouseup", function() {
/* $currentElement = whatever element the caret is inside. */
});
$(this).on("keyup", …Run Code Online (Sandbox Code Playgroud)