contenteditable
Gmailのメモウィジェットのように、カレットをノードの最後に移動する必要があります。
StackOverflowでスレッドを読みましたが、これらのソリューションは入力の使用に基づいており、contenteditable
要素では機能しません。
contenteditable
Gmailのメモウィジェットのように、カレットをノードの最後に移動する必要があります。
StackOverflowでスレッドを読みましたが、これらのソリューションは入力の使用に基づいており、contenteditable
要素では機能しません。
Geowa4 のソリューションはテキストエリアでは機能しますが、contenteditable 要素では機能しません。
このソリューションは、キャレットを contenteditable 要素の最後に移動するためのものです。contenteditable をサポートするすべてのブラウザーで動作するはずです。
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
次のようなコードで使用できます。
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
フォーカス イベントに応じてカーソルを編集可能なスパンの最後に移動する:
moveCursorToEnd(el){
if(el.innerText && document.createRange)
{
window.setTimeout(() =>
{
let selection = document.getSelection();
let range = document.createRange();
range.setStart(el.childNodes[0],el.innerText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
,1);
}
}
そして、イベントハンドラーでそれを呼び出します(ここで反応します):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
との問題は、最初に入力を開始すると解決されますcontenteditable
<div>
。<span>
これに対する 1 つの回避策は、div 要素とその関数でフォーカス イベントをトリガーし、div 要素に既にあったものをクリアして再入力することです。このようにして問題は解決され、最終的に範囲と選択を使用してカーソルを最後に置くことができます。私のために働いた。
moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;
if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}
HTML コードの場合:
<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>