LoginSignup
1
1

More than 5 years have passed since last update.

JavaScript で選択できないテキストをクリップボードへコピーする方法

Last updated at Posted at 2019-02-02

クリップボードにコピーする機能のサンプルコード

<html>
    <head>
        <meta charset="UTF-8">
        <script>
            document.onselectstart = function() {
               return false;
            }
            function copyTextToClipboard(element) {
                var copyTarget = document.getElementById(element);
                var copyArea = document.createElement("input");
                copyArea.value = copyTarget.textContent;
                document.body.appendChild(copyArea);
                copyArea.select();
                document.execCommand("Copy");
                if (!('remove' in Element.prototype)) {
                    Element.prototype.remove = function () {
                        if (this.parentNode) {
                            this.parentNode.removeChild(this);
                        }
                    };
                }
                copyArea.remove();
                alert(copyTarget.textContent + "をコピーした。");
            }
        </script>
    </head>
    <body>
        <span id="copyTarget">テキスト</span> 
        <button onclick="copyTextToClipboard('copyTarget')">コピー</button>
    </body>
</html>

サンプルスナップショット

copyTarget.png

1
1
0

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
1
1