【javascript】マウスで選択した文字列の取得 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.textContentに document.getSelection()を指定すれば、選択した文字列が反映されます。 ここではtoString()にしなくても大丈夫です。
const textarea = document.querySelector("textarea");
const getSelected = function () {
let selected = document.getSelection();
textarea.textContent += selected;
};
参考
まとめ
以上、選択範囲の文字列を取得する方法を紹介しました。 意外と簡単に、数行のjavascriptで取得できるんですね~。
- document.getSelection()でSlectionを取得
- document.getSelection().toString()で選択範囲の文字列を取得
- textarea.textContent = document.getSelection() でテキストエリアに書き出すことができる。