▲TOPへ戻る

【javascript】マウスで選択した文字列の取得 getSelection

getSelection マウスで選択 取得

やりたいこと

以下のようにマウスで選択した文字列を取得し、 textareaに書き出す方法について紹介します。

マウスで選択した文字列の取得

2行目 : document.getSelection(); で、Selectionを取得。

3行目 : document. getSelection().toString(); で、マウスで選択した文字列を取得できます。

7行目 : マウスを話した時(mouseup)にイベントを処理します。

このページ上で、マウスを文字列で選択し、コンソールを確認してみてください。

const getSelected = function () {
  let selection = document.getSelection();
  console.log(selection);
  console.log(selection.toString());
};

document.addEventListener("mouseup", getSelected);

選択した文字列をtextareaに書き出す

1行目 : textareaを取得

5行目 : textarea.textContentdocument.getSelection()を指定すれば、選択した文字列が反映されます。 ここではtoString()にしなくても大丈夫です。

const textarea = document.querySelector("textarea");

const getSelected = function () {
  let selected = document.getSelection();
  textarea.textContent += selected;
};

参考

js
【javascript】よく使う演算子の使い方 "++", "--", "+=", "-=", "%", "&&", "||"
html
【HTML】【CSS】iframeタグの使い方 HTMLファイルを埋め込む方法

まとめ

以上、選択範囲の文字列を取得する方法を紹介しました。 意外と簡単に、数行のjavascriptで取得できるんですね~。

  1. document.getSelection()でSlectionを取得
  2. document.getSelection().toString()で選択範囲の文字列を取得
  3. textarea.textContent = document.getSelection() でテキストエリアに書き出すことができる。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ