0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptでコピー機能の作成

Last updated at Posted at 2025-02-13

解読するコード

コピーボタンをクリックすると「コピーするテキスト」がクリップボードにコピーされる仕様である。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>コピー機能テスト</title>
</head>
<body>
    <button onclick="copyText()">コピー</button>
    <p id="text">コピーするテキスト</p>

    <script>
        function copyText() {
            let text = document.getElementById("text").innerText;
            navigator.clipboard.writeText(text).then(() => {
                alert("コピーされました");
            });
        }
    </script>
</body>
</html>

1.ワンクリック属性

<button onclick="copyText()">コピー</button>ボタンを押すとcopyText()関数が呼び出されます。

2.text変数に格納

let text = document.getElementById("text").innerText;getElementById("text")でid属性がtextのタグを取得しshinnerTextプロパティをtext変数に格納しています。つまりタグを指定して、その中身を取り出し格納しているという流れになります。

3.writeTextメソッドによりクリップボードにコピー

navigator.clipboard.writeText(text).により先ほど格納したtext変数の値をクリップボードにコピーしています。

4.その他の注意事項

innerTextとvalueの使い分け
今回のようにp,div,spanなどのタグ内のテキストを取得する際にはinnerTextを使用します。一方、input,textareaなど入力値のテキストを取得する際にはvalueを使用します。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?