コピーをウェブサイトでクリップボードに実装する方法


この記事では、我々はどのように我々のウェブサイト上でクリップボード機能にコピーを実装することができますを参照してください.をクリックします.Copy ボタンは、段落タグの内容/テキストは、我々は我々のシステムの任意の場所に貼り付けることができるクリップボードにコピーする必要があります.
コードパーツに直接ジャンプしましょう.
私は、あなたがHTML、JavaScriptとDOM操作の基礎知識を持っていると仮定します.

👨‍💻 コード
パラグラフコンテンツとコピーボタンを表示するために、非常に簡単なHTMLコードを書きます.index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Copy To Clipboard</title>
</head>

<body align="center">
    <p id="content">The text to be copied.</p>
    <button id="copy">Copy Text</button>
    <script src="./script.js"></script>
</body>

</html>
script.js
// Reference of the paragraph tag
const content = document.getElementById("content");

// Reference of the copy button
const copyBtn = document.getElementById("copy");

// Copy button's onclick handler
copyBtn.onclick = copyToClipboard;

// Method responsible for copying the content
function copyToClipboard() {
    navigator.clipboard
        .writeText(content.innerText)
        .then(() => alert("Copied to clipboard"))
        .catch((e) => alert(e.message));
}
だからまず最初に参照しているparagraph タグとタグcopy ボタンをクリックし、onclick ハンドラcopy ボタン.
をクリックします.copy ボタン、copyToClipboard メソッドが呼び出されます.

クリップボードにコピー
インサイドcopyToClipboard 方法は、クリップボードAPIを使用しています.

The Clipboard API can be used to implement cut, copy, and paste features within a web application.

  • システムクリップボードは、グローバルnavigator.clipboard プロパティ.
  • The writeText クリップボードオブジェクトのメソッドは、クリップボードに書き込まれる引数として文字列値を期待します.
  • クリップボードの内容が更新されると、解決される約束を返します.どんなエラーの場合でも、約束は拒絶されます.
  • ...
    navigator.clipboard
        .writeText(content.innerText)
        .then(() => alert("Copied to clipboard"))
        .catch((e) => alert(e.message));
    ...
    
    だから私たちはinner text への段落タグのwriteText そして、約束が解決されるならば、テキストはコピーされました.

    ✨ ボーナス
    同様に、我々は実装することができますcut 機能.
    テキストがクリップボードにコピーされた後、段落タグの内側のテキストを空の文字列で上書きします.
    navigator.clipboard
        .writeText(content.innerText)
        .then(() => {
            // Overwriting with an empty string
            content.innerText = "";
            alert("Copied to clipboard");
        })
        .catch((e) => alert(e.message));
    

    🔗 デモ
    ギタブレポLink
    試してみてください.Link

    Originally published on blog.bibekkakati.me


    読書ありがとう🙏
    あなたがこの記事を楽しんでいるか、それが役に立つとわかるならば、それに親指を与えてください👍
    お気軽に👋
    陳川
    あなたが私の仕事が好きで、それをサポートしたいならば、あなたはここでそれをすることができます.本当に感謝します.