15

次のような contenteditable div があります。

<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>

次のコードを使用します。

<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>

div 内でキャレットを移動するときにボタンをクリックすると、div 内のキャレットの実際の位置 (オフセット) が返されます。

問題は、contenteditable div を input type=text または password コントロールに置き換え、contenteditable プロパティを true のままにしてボタンをクリックすると、常にゼロになることです。どうしてこれなの?

ご覧いただきありがとうございます。

4

3 に答える 3

17

ほとんどのブラウザーでwindow.getSelection()は、ドキュメント内のテキスト ノードおよび要素内の選択範囲でのみ機能します。<input>および<textarea>要素内のテキストには適用されません(ただし、WebKitwindow.getSelection().toString()では、フォーカスされたテキスト入力またはテキストエリア内で選択されたテキストが返されます。http://jsfiddle.net/PUdaS/を参照してください)。入力内の選択を取得するには、入力のselectionStartおよびselectionEndプロパティを使用します。

<input type="text" id="test" value="Some text">

<input type="button" value="Click me"
    onclick="alert(document.getElementById('test').selectionEnd);">

selectionStartバージョン 8 までの IE はおよびselectionEndプロパティをサポートしておらず、別のより複雑なソリューションが必要であることに注意してください。IE はどちらもサポートしていないためwindow.getSelection()、このコードは元のコードが動作するすべてのブラウザーで動作します。

于 2011-02-22T00:05:14.790 に答える
1

これは、JavaScript ではなくブラウザーの設計上の癖であるため、使用しているブラウザーに大きく依存します。

あなたの場合、ハイライト表示されている<input type="button">間に をクリックすると、<div>ハイライト表示された<div>ままになります。ただし、またはが強調表示され<input type="button">ているときに をクリックすると、フォーカスが失われ、強調表示が削除されます (したがって、コードが失敗します)。<input type="text"><textarea>

あなたが達成しようとしていることを詳しく見て、この問題にどのように取り組んでいるかを再考することを検討します.

于 2011-02-21T23:05:53.603 に答える
0

2 備考:

<input... >タグはタグではなく、それに応じて閉じる<input ... />必要があります。それ以外の場合は、タグを使用する必要<button>があります (ただし、X ブラウザーのコンプライアンス上の理由から、タグ内では使用しないでください) 。

終わりのないストーリーに入りたくない場合は、次のようにポイントを処理する方法を再考することができます:そのまま<div>にして、その上で DOM イベントを起動します (タグで onclick イベントを使用する代わりに) . フランス語が読めるなら、ここにたくさんの例をまとめました。この方法は最初の方法よりもかなり重くなりますが、DOM で必要に応じてイベントを起動したり、コールバック関数を使用したりできるため、その後ははるかに強力になります。

原則は次のとおりです:
一方で HTML ページ

<div id="test"...>Lorem..</div>  
<script src="..."/>  

一方、邪魔にならない JavaScript コード

// your event handler here
function Dothisorthat(e) {
 // pop up the dom content or edit it or start an ajax request or whatever you need here
 return false;
}

// This is read in the third place  
function attacherAction() {
// Attach the action "Dothisorthat" on the event "onclick" occuring on your div "test"
id ='test'; // your div id
if (document.getElementById(id)) {
       zLink = document.getElementById(id);
       zLink.onclick = function() {
           Dothisorthat(this); // in your case, you can write a small function to pop up or edit the div content
       }
   }
}  
// This is read second
function addLoadEvent(func) {  
  var oldonload = window.onload;  
  if (typeof window.onload != 'function') {  
    window.onload = func;  
  } else {  
    window.onload = function() {  
      if (oldonload) {  
        oldonload();  
      }  
      func();
    }
  }
}  
    // This is read first
addLoadEvent(attacherAction);  

それが役立つことを願っています

于 2011-02-22T00:05:39.953 に答える