我很难做一些简单的事情:获取用户在段落中点击的插入位置。这很复杂,因为我正在根据用户输入在上下文中创建和销毁WYSIWYG文本编辑器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>
在初始化redactor之后,我想将光标定位在用户最初点击的位置。很简单,对吧?好吧,在我的点击处理程序(附加到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>
DIV
并将其设为contenteditable='true'
<p>
内单击
<p>
在步骤1&amp; 3,“选择”显然尚未传递给<p>
。我认为这是因为在这些点上,有问题的<p>
在其祖先中没有任何contenteditable='true'
因此它本身就不能真正具有“选择”。
当用户点击一个标签时,如何将鼠标光标下的插入位置放在一个不可信的<p>
标记内?
非常感谢任何帮助/建议!
(不幸的是,Redactor不是免费提供的,所以我不能在jsFiddle示例中包含它)
这些“node”div也使用jQueryUI的可拖动和可放置的小部件。禁用这些后,处理程序输出选择的预期值...有趣。不幸的是,拖放功能是一项要求..
答案 0 :(得分:0)
我不知道这是否有用,但在获得选择之前尝试添加一个小setTimeout
。这应该使它在点击之后给你选择,然后在那个回调中你可以初始化编辑器。