クリップボードにテキストをコピーする

2776 ワード

このポストでは、Webページ上のテキストをクライアントデバイスに直接コピーする方法を学びます.
HTMLパーツ
これは選択テキストでのみ動作します.
HTMLファイルを作成し、下のコードをファイルにコピーします.

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- The text field -->
<input type="text" value="text me to copy" id="mycopy">

<!-- The button used to copy the text -->
<button onclick="myFunction()">Copy text</button>
</body>
</html>

上記のHTMLコードは何ですか

<input type="text" value="text me to copy" id="mycopy">

  • これは、私たちがコピーしたいテキストの値と属性ID =“mycopy”を含んでいる入力タグです.
  • 
    <button onclick="myFunction()">Copy text</button>
    
    
  • 上記のボタンタグには、ユーザがボタンをクリックしたときにテキストがコピーされます.
  • ジャバスクリプト
    
    <script>
    function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("mycopy");
    
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */
    
      /* Copy the text inside the text field */
      document.execCommand("copy");
    
      /* Alert the copied text */
      alert("Copied the text: " + copyText.value);
    }
    </script>
    
    
    上記のスクリプトコードは以下のようになります.
  • 私たちはmyfunction ()関数を作成します.var copyText = document.getElementById("mycopy");

  • コピーするテキストのIDを取得します
  • copyText.select();

  • これは入力/テキスト領域の自動を選択します.
  • 
    copyText.setSelectionRange(0, 99999);
    
    
  • これはテキストの範囲を選択することです
  • 
    document.execCommand("copy");
    
    

  • このコードはクリップボードにテキストをコピーします.
  • 
    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    </head>
    <body>
    <!-- The text field -->
    <input type="text" value="text me to copy" id="mycopy">
    
    <!-- The button used to copy the text -->
    <button onclick="myFunction()">Copy text</button>
    
    <script>
    function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("mycopy");
    
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */
    
      /* Copy the text inside the text field */
      document.execCommand("copy");
    
      /* Alert the copied text */
      alert("Copied the text: " + copyText.value);
    }
    </script>
    </body>
    </html> 
    
    
    コメントを残す