JavaScript で非常に基本的なリッチ テキスト エディターを作成しようとしていますが、選択に問題があります。基本的に、これは contentEditable <div> であるため、ユーザーが Web ページから書式設定済みのテキストを貼り付けても、書式設定が剥がれることはありません。
簡単に破れるハックは、Ctrl + V が押されたときに <textarea> にフォーカスを移すことです。テキストはそこに貼り付けられます。次に onkeyup、フォーカスを <div> に戻し、内容をコピーして、入ったものをすべて削除します。 <テキストエリア> に。
これは簡単ですが、contentEditable &;t;div> にフォーカスを戻すと、キャレットの位置が貼り付け直後ではなく先頭になります。私は選択とそれを理解するのに十分な知識がないので、助けていただければ幸いです。これが私のコードです:
// Helpers to keep track of the length of the thing we paste, the cursor position
// and a temporary random number so we can mark the position.
editor_stuff =
{
cursor_position: 0,
paste_length: 0,
temp_rand: 0,
}
// On key up (for the textarea).
document.getElementById("backup_editor").onkeyup = function()
{
var main_editor = document.getElementById("question_editor");
var backup_editor = document.getElementById("backup_editor");
var marker_position = main_editor.innerHTML.search(editor_stuff.temp_rand);
// Replace the "marker" with the .value of the <textarea>
main_editor.innerHTML = main_editor.innerHTML.replace(editor_stuff.temp_rand, backup_editor.value);
backup_editor.value = "";
main_editor.focus();
}
// On key down (for the contentEditable DIV).
document.getElementById("question_editor").onkeydown = function(event)
{
key = event;
// Grab control + V end handle paste so "plain text" is pasted and
// not formatted text. This is easy to break with Edit -> Paste or
// Right click -> Paste.
if
(
(key.keyCode == 86 || key.charCode == 86) && // "V".
(key.keyCode == 17 || key.charCode == 17 || key.ctrlKey) // "Ctrl"
)
{
// Create a random number marker at the place where we paste.
editor_stuff.temp_rand = Math.floor((Math.random() * 99999999));
document.getElementById("question_editor").textContent += editor_stuff.temp_rand;
document.getElementById("backup_editor").focus();
}
}
したがって、私の考えは、カーソル位置 (整数) をヘルパー配列 ( editor_stuff.cursor_position
) に格納することです。
NB私は一日中SOで他の回答を見てきましたが、それらのどれも私のために働くことができません。