ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScriptでテキストボックスから選択したテキストを取得するにはどうすればよいですか?

JavaScriptでテキストボックスから選択したテキストを取得するにはどうすればよいですか?

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-24 09:22:02772ブラウズ

How to Retrieve Selected Text from a Textbox in JavaScript?

JavaScript でテキストボックスから選択したテキストを取得する

Web フォームを操作する場合、多くの場合、ユーザーが選択したテキストをテキストボックスから取得する必要があります。テキストボックス。これは、JavaScript と次の手順を使用して実行できます。

ステップ 1: ブラウザ間の互換性を実装する

さまざまなブラウザ間での互換性を確保するには、次のコードを使用して決定します。選択されたテキストを取得するための推奨方法:

<code class="js">function getSelection(textComponent) {
  if (textComponent.selectionStart !== undefined) {
    // Standards-compliant version
    return textComponent.value.substring(textComponent.selectionStart, textComponent.selectionEnd);
  } else if (document.selection !== undefined) {
    // Internet Explorer version
    textComponent.focus();
    var sel = document.selection.createRange();
    return sel.text;
  }
}</code>

ステップ 2: イベントで選択されたテキストを取得する

ユーザーがボタンをクリックしたときに、またはユーザーが選択したテキストを取得するには他の UI 要素の場合は、イベント リスナーを要素にアタッチします。

<code class="js">document.getElementById("button").addEventListener("click", function() {
  var selectedText = getSelection(document.getElementById("textbox"));
  alert(selectedText);
});</code>

ステップ 3: Internet Explorer の不具合を処理する

Internet Explorer 6 では、テキストが正しく選択されました。次のコードを使用します。

<code class="js">document.onkeydown = function (e) {
  getSelection(document.getElementById("textbox"));
};</code>

例:

次の例は、実際の機能を示しています。

<code class="html"><input id="textbox" type="text" value="Lorem ipsum dolor sit amet">
<button id="button">Get Selected Text</button>

<script>
  document.getElementById("button").addEventListener("click", function() {
    var selectedText = getSelection(document.getElementById("textbox"));
    alert(selectedText);
  });
</script></code>

次の手順に従います。を使用すると、JavaScript のテキストボックスから選択したテキストを効果的に取得でき、ブラウザ間の互換性を確保し、Internet Explorer の癖に対処できます。

以上がJavaScriptでテキストボックスから選択したテキストを取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。