我很难做一些应该很简单的事情:获取用户在段落中单击的插入符号位置。这很复杂,因为我正在创建和销毁所见即所得文本编辑器的实例 Redactor基于用户输入的上下文,这会修改 DOM。
我的结构:
<div class='node'>
<div class='hierarchy'></div>
<div class='content'>
<h2>Test Heading</h2>
<p>Content that user might click on. Need to find position where I should insert cursor after initialising Redactor</p>
</div>
</div>
当用户单击文本时,我会初始化一个 redactor 实例,它会像这样修改 DOM:
<div class='node'>
<div class="hierarchy"></div>
<div class="redactor_box">
<div id="redactorToolbar">... ul etc ...</div>
<div class="content redactor_editor" contenteditable="true">
<h2>Test Heading</h2>
<p>Content that user might click on. Need to find position where I should insert cursor after initialising Redactor</p>
</div>
<textarea dir="ltr" style="height: 90px; display: none;"></textarea>
</div>
</div>
编辑器初始化后,我想将光标定位在用户最初单击的位置。很简单,对吧?好吧,在我的点击处理程序(附加到 div.node)中,window.getSelection()
返回单击之前插入符号的位置:
Node.prototype.onClick = function (e, ui) {
var $el = $(this),
node = $el.data('node'),
document = node.document,
selection = window.getSelection();
console.log('rangeCount: ', selection.rangeCount);
console.log('type: ', selection.type);
console.log('anchorOffset: ', selection.anchorOffset);
if ($el.has('.redactor_box').length <= 0) {
document.setRedactor(node);
}
};
比如说我:
- 点击
<p>
在第 5 个字符处- 打印“rangeCount:0,类型:None,anchorOffset:0”
- 初始化 Redactor,包装内容
DIV
并使其contenteditable='true'
- 点击
<p>
内部在字符位置 108- 打印“rangeCount:1,类型:插入符,anchorOffset:108”(预期)
- 单击不同的节点
<p>
在第 5 个字符处- 打印“rangeCount:1,类型:插入符,anchorOffset:108”(未预期)
- 销毁编辑器并在第二个节点周围重新创建
在步骤 1 和 3 中,“选择”显然尚未传递给 <p>
。我认为这是因为在这些点上,<p>
有问题的没有任何 contenteditable='true'
在它的祖先中,所以它本身不可能真正有“选择”。
我的问题:
如何在非 contenteditable'd <p>
中获取鼠标光标下的插入符号位置当用户点击一个标签时?
非常感谢任何帮助/建议!
(不幸的是,Redactor 不是免费提供的,因此我无法将其包含在 jsFiddle 示例中)
更新
这些“节点”div 也使用 jQueryUI 的可拖动和可放置小部件。禁用这些后,处理程序会输出选择的预期值......有趣。不幸的是,拖/放功能是必需的..
最佳答案
我不知道这是否有效,但在获取选择之前尝试添加一个小的setTimeout
。这应该会导致它在点击后为您提供选择,然后您可以在该回调中初始化编辑器。
关于javascript - 获取点击事件上的插入符位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22185711/