コードのコピーボタン | Java Script

Copy Code to Clipboard


// コピーされるコード
$(document).ready( function () {
   $("a[href^='http']:not([href*='" + location.hostname + "'])").attr('target', '_blank');
})

HTML

    <button id="copyButton">コードをコピー</button>

Java Script

    // ページが読み込まれた後の処理
    document.addEventListener("DOMContentLoaded", function () {
        // "コードをコピーする" ボタンをクリックしたときの処理
        document.getElementById("copyButton").addEventListener("click", function () {
            // コピー対象のテキストを選択
            const codeToCopy = document.querySelector("pre");
            const range = document.createRange();
            range.selectNode(codeToCopy);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);

            // テキストをクリップボードにコピー
            try {
                document.execCommand("copy");
                alert("コードがクリップボードにコピーされました。");
            } catch (err) {
                alert("コードのコピーに失敗しました。手動でコピーしてください。");
            } finally {
                window.getSelection().removeAllRanges();
            }
        });
    });

Comments

Popular posts from this blog