jquery formのテキストフィールドの内容をクリップボードにコピーしたい
作成日:2019-02-07, 更新日:2019-02-07
基本
2019-02-07時点。
1.「clipboard.js」自体を手に入れる
2.記述
「clipboard.js」自体を手に入れる
「clipboard.js」にアクセスして、「Install」に従う。
▼もしくは「Install」のトコに下記があるのでダウンロード
Or if you're not into package management, just download a ZIP file.
必要なのは「dist/clipboard.min.js」。
※中身を解読したいなら「clipboard.js」。
記述
・「clipboard.min.js」を読み込ませる
基本
▼トリガーになる要素を引数にする
<script> new ClipboardJS('.btn'); </script>
コピーさせる文章のテキストフィールドを指定
<input id="foo" value="https://github.com/zenorocha/clipboard.js.git"> <button class="btn" data-clipboard-target="#foo">Copy to clipboard</button>
Cut text from another element・・・不明
<textarea id="bar">Mussum ipsum cacilds...</textarea> <button class="btn" data-clipboard-action="cut" data-clipboard-target="#bar">Cut to clipboard</button>
ボタンにコピーさせる文章を記載
<button type="button" class="btn" data-clipboard-text="Just because you can doesn't mean you should — clipboard.js">Copy to clipboard</button>
応用:コピーしたいテキスト指定
new ClipboardJS('.btn', { text: function(trigger) { return trigger.getAttribute('aria-label'); } });
対象の前の要素から取得
▼対象の前にあるinputタグのvalueを取得
new ClipboardJS('.btn', { text: function(trigger) { return trigger.previousElementSibling.value; } });
※「previousElementSibling」が前の要素っぽい。「nextElementSibling」もいる。
「return 〇〇〇」のトコで適当な文字列を返す感じで良いっぽい。