ユーザーが段落内でクリックしたキャレット位置を取得するという、単純であるべきことを行うのに苦労しています。DOM を変更するユーザー入力に基づいて、WYSIWYG テキスト エディターRedactorのインスタンスをコンテキストに応じて作成および破棄しているため、これは複雑です。
私の構造:
<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>
ユーザーがテキストをクリックすると、次のように DOM を変更する redactor のインスタンスが初期化されます。
<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>
char 5 を クリックします。- 「rangeCount: 0、type: None、anchorOffset: 0」を出力します
- Redactor を初期化し、コンテンツ
DIV
をラップして作成しますcontenteditable='true'
<p>
at char 位置 108 内をクリックします。- 「rangeCount: 1、type: Caret、anchorOffset: 108」を出力 (予想)
<p>
char 5 で 別のノードをクリックします。- 「rangeCount: 1、type: Caret、anchorOffset: 108」を出力 (予期しない)
- リダクターを破棄し、2 番目のノードの周りを再作成します
ステップ 1 と 3 では、「選択」は明らかに に渡されていません<p>
。これは、これらの時点で、<p>
問題のcontenteditable='true'
祖先には何もないため、実際には「選択」自体を持つことができないためだと思います。
私の質問:
<p>
ユーザーがクリックしたときに、非コンテンツ編集可能タグ内のマウスカーソルの下のキャレット位置を取得するにはどうすればよいですか?
どんな助け/アドバイスも大歓迎です!
(残念ながら、Redactor は自由に利用できないため、jsFiddle の例に含めることはできません)
アップデート
これらの「ノード」div は、jQueryUI のドラッグおよびドロップ可能なウィジェットも使用しています。これらを無効にすると、ハンドラーは選択の期待値を出力します...興味深いです。残念ながら、ドラッグ アンド ドロップ機能は必須です。