LoginSignup
130

More than 5 years have passed since last update.

「クリップボードにコピー」を実装する

Last updated at Posted at 2015-11-11

clipboard.js を使う

clipboard.js — Copy to clipboard without Flash

↓ github にあるこんな感じのものを作ります。

clipboard_js.png

デモを下記に置きました。

HTMLは下記のような感じ。
ボタンの data-clipboard-target="XXX" の部分にコピー対象のエレメントを指定しておく。

<html>

  <head>
    <meta charset="UTF-8" />
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/clipboard.js/1.5.3/clipboard.min.js"></script>
    <script>
        $(function () {
          var clipboard = new Clipboard('.btn');
        });
    </script>
  </head>

  <body>

    <!-- コピー対象 -->
    <input id="foo" value="https://github.com/zenorocha/clipboard.js.git" size="60">

    <!-- コピーボタン -->
    <button class="btn" data-clipboard-target="#foo">
        クリップボードにコピー
    </button>

  </body>
</html>


このままだと、コピー対象文字列が選択状態のままになるので、選択状態を解除するには、success のイベントでclearSelection を呼ぶ。

var clipboard = new Clipboard('.btn');

clipboard.on('success', function(e) {
    e.clearSelection();
});

失敗の時のコールバックとかもあるみたい。

詳細は下記参照

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
130