2012-03-17 7 views
2

私はSOとさまざまなサイトを一日中検索していますが、私の問題に一応合った多くの回答が出てきましたが、実装に問題がありますソリューション。JavaScript window.getSelection()は把握できません

  1. 私はリッチテキストエディタを構築しました。
  2. 書式が設定された「貼り付け」データを正しく処理する必要があります。
  3. 私はonpaste = "return false"で貼り付けを無効にしました。
  4. Ctrl + Vでは、非表示のテキストエリアにフォーカスが与えられ、テキストがユーザーによって貼り付けられ、textarea.valueが取り込まれ、エディタ(contentEditable div)にコピーされます。
  5. 私はIEでこれを行うことができますが、残りはできません。

私の問題は、window.getSelection()オブジェクトが標準準拠のブラウザでどのように動作するのか理解できません。私が望むのは、新しく貼り付けたtextarea.valueを、JavaScriptを介してエディタにコピーし、フォーカスとカーソル(キャレット)の位置を保持することです。したがって、点滅するカーソルはペーストの最後に残るはずです。

function handle_paste_keydown(key) 
{ 
    if(
     (key.keyCode == 86 || key.charCode == 86) && 
     (key.keyCode == 17 || key.charCode == 17 || key.ctrlKey) // if "Ctrl+V" is pressed. 
    ) 
    { 
     var get_paste_selection_range; 

     if(document.selection) 
     { 
      get_paste_selection_range = document.selection.createRange();     
      document.getElementById("paste_textarea").style.display = "block"; 
      document.getElementById("paste_textarea").focus();    

      document.getElementById("paste_textarea").onkeyup = function() 
      { 
       // insert the .value of the textarea at the cursor position in the editor. 
       get_paste_selection_range.text += document.getElementById("paste_textarea").value;    
       document.getElementById("paste_textarea").style.display = "none"; 

       // retain focus and cursor position      
       get_paste_selection_range.select();   
      } 
     } 
     else if(window.getSelection())  
     { 
      document.getElementById("paste_textarea").style.display = "block"; 
      document.getElementById("paste_textarea").focus(); 

      document.getElementById("paste_textarea").onkeyup = function() 
      { 
       // How do I handle this? 
       document.getElementById("paste_textarea").style.display = "none"; 
      } 
     } 
    } 
document.getElementById("paste_textarea").value = ""; 
} 

Cany誰が助ける:

は私が残りをIEでこの目標をachives次のコードを書かれていますが、していませんか?ありがとう!

編集:ライブバージョンへのリンクを追加しました。あなたは何が起こっているかを見ることができます。 Internet Explorerや他のブラウザでこれを試してください。何が起きているのかを正確に見ることができます。注:私は隠しテキストエリアをCtrl + Vで表示するようにしました。何が起こっているのかをよりよく把握し、Ctrl + Vキーを押してボックスを画面に保持します。

http://gameprogrammingworkshop.com/Java/Stack%20Overflow%20Error!/index.php?id=null

答えて

0
... 
else if (window.getSelection) { 
    var selection = window.getSelection(), 
     get_paste_selection_range = selection.getRangeAt(0); 
    var new_text = selection.toString() + document.getElementById("paste_textarea").value; 

    // retain your focus 
} 
+0

こんにちは。ご回答ありがとうございますが、私はあなたのコードを動作させることができません。私は今、数時間試してきたし、何をすべきかわからない。私はJavaScriptの初心者ですが、元の投稿を自分のコードのライブバージョンへのリンクで編集しているため、何が起こっているのか、私が達成しようとしていることを正確に見ることができます。あなたが見ることができない/したくない場合は、お時間をいただきありがとうございます。 – George88

関連する問題